Compare commits
10
Commits
d56d3d6b5b
..
v2.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c502da2dfb | ||
|
|
3b45c14ded | ||
|
|
255066eefa | ||
|
|
74d7910fec | ||
|
|
bcb885c878 | ||
|
|
3f59b905c7 | ||
|
|
869b09f8a9 | ||
|
|
bdfc4043f8 | ||
|
|
caf77819a2 | ||
|
|
47e51e10f0 |
@@ -18,7 +18,6 @@ from logging.handlers import RotatingFileHandler
|
||||
from flask_socketio import SocketIO, emit
|
||||
|
||||
# --- DYNAMIC BASE PATH ---
|
||||
# Calcola automaticamente la directory esatta in cui si trova questo file (app.py)
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# --- PATHS ---
|
||||
@@ -41,10 +40,9 @@ logging.basicConfig(
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
logger = logging.getLogger("FleetHub")
|
||||
# Silence HTTP request spam (GET /api/states 200 OK)
|
||||
logging.getLogger('werkzeug').setLevel(logging.ERROR)
|
||||
|
||||
# --- CONFIG (caricata subito: serve a secret_key, CORS, utente di default, ecc.) ---
|
||||
# --- CONFIG ---
|
||||
config_lock = threading.Lock()
|
||||
|
||||
def read_config():
|
||||
@@ -52,7 +50,6 @@ def read_config():
|
||||
return json.load(f)
|
||||
|
||||
def write_config(cfg):
|
||||
"""Scrittura atomica di config.json (file temporaneo + replace), mantenendo i permessi."""
|
||||
tmp = CONFIG_PATH + '.tmp'
|
||||
with config_lock:
|
||||
with open(tmp, 'w') as f:
|
||||
@@ -64,10 +61,9 @@ def write_config(cfg):
|
||||
os.replace(tmp, CONFIG_PATH)
|
||||
|
||||
config = read_config()
|
||||
web_cfg = config.get('web', {}) # opzionale: secret_key, cookie_secure, session_hours, cors_origins, trust_proxy
|
||||
web_cfg = config.get('web', {})
|
||||
|
||||
def get_secret_key():
|
||||
"""Chiave di sessione: da FLEET_SECRET_KEY, da config.json oppure generata e salvata."""
|
||||
key = os.environ.get('FLEET_SECRET_KEY') or config.get('secret_key')
|
||||
if not key or key == 'ari_fvg_secret_ultra_secure':
|
||||
key = secrets.token_hex(32)
|
||||
@@ -83,7 +79,7 @@ def init_db():
|
||||
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||
c = conn.cursor()
|
||||
|
||||
c.execute('PRAGMA journal_mode=WAL;') # <-- MAGIC: Enable simultaneous read/write!
|
||||
c.execute('PRAGMA journal_mode=WAL;')
|
||||
|
||||
c.execute('''CREATE TABLE IF NOT EXISTS radio_logs
|
||||
(id INTEGER PRIMARY KEY AUTOINCREMENT, timestamp DATETIME, client_id TEXT,
|
||||
@@ -122,7 +118,6 @@ def init_db():
|
||||
def_pass = adm_cfg.get("default_pass", "")
|
||||
generated = False
|
||||
if not def_pass or def_pass == "admin123":
|
||||
# niente password di default note: ne generiamo una casuale
|
||||
def_pass = secrets.token_urlsafe(9)
|
||||
generated = True
|
||||
|
||||
@@ -149,11 +144,11 @@ def load_ids():
|
||||
if os.path.exists(DMR_IDS_PATH):
|
||||
with open(DMR_IDS_PATH, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
for l in f:
|
||||
l = l.replace('"', '') # Rimuove eventuali virgolette
|
||||
l = l.replace('"', '')
|
||||
if ',' in l: p = l.strip().split(',')
|
||||
elif '\t' in l: p = l.strip().split('\t')
|
||||
elif ';' in l: p = l.strip().split(';')
|
||||
else: p = l.strip().split() # Cerca gli spazi normali
|
||||
else: p = l.strip().split()
|
||||
|
||||
if len(p) >= 2 and p[0].strip().isdigit():
|
||||
new_dmr[p[0].strip()] = p[1].strip()
|
||||
@@ -166,7 +161,6 @@ def load_ids():
|
||||
if len(p) >= 2 and p[0].strip().isdigit():
|
||||
new_nxdn[p[0].strip()] = p[1].strip()
|
||||
|
||||
# Un file vuoto/corrotto non deve cancellare un database valido già in memoria
|
||||
if new_dmr: user_db = new_dmr
|
||||
if new_nxdn: nxdn_db = new_nxdn
|
||||
|
||||
@@ -208,13 +202,11 @@ app.secret_key = get_secret_key()
|
||||
app.config.update(
|
||||
SESSION_COOKIE_HTTPONLY=True,
|
||||
SESSION_COOKIE_SAMESITE='Lax',
|
||||
SESSION_COOKIE_SECURE=bool(web_cfg.get('cookie_secure', False)), # metti true se servi la dashboard solo in HTTPS
|
||||
SESSION_COOKIE_SECURE=bool(web_cfg.get('cookie_secure', False)),
|
||||
PERMANENT_SESSION_LIFETIME=int(web_cfg.get('session_hours', 12)) * 3600,
|
||||
)
|
||||
|
||||
# --- NOTIFICHE WEBSOCKET "COALESCED" ---
|
||||
# Molti messaggi MQTT ravvicinati generano UN solo evento ogni NOTIFY_DELAY secondi
|
||||
# (altrimenti ogni browser farebbe 3 richieste HTTP per ogni messaggio).
|
||||
# --- NOTIFICHE WEBSOCKET ---
|
||||
NOTIFY_DELAY = 0.3
|
||||
_notify_lock = threading.Lock()
|
||||
_notify_pending = set()
|
||||
@@ -236,6 +228,7 @@ def notify_update(event='dati_aggiornati'):
|
||||
timer = threading.Timer(NOTIFY_DELAY, _fire)
|
||||
timer.daemon = True
|
||||
timer.start()
|
||||
|
||||
client_states = {}
|
||||
device_configs = {}
|
||||
client_telemetry = {}
|
||||
@@ -245,6 +238,7 @@ last_seen_reflector = {}
|
||||
network_mapping = {}
|
||||
node_info = {}
|
||||
node_general = {}
|
||||
node_versions = {}
|
||||
|
||||
if os.path.exists(CACHE_FILE):
|
||||
try:
|
||||
@@ -253,10 +247,6 @@ if os.path.exists(CACHE_FILE):
|
||||
|
||||
active_calls = {}
|
||||
|
||||
# --- DIAGNOSTICA: ultimo messaggio MQTT ricevuto, per nodo e per tipo ---
|
||||
# mmdvm -> mmdvm/<id>/json (eventi radio: TX, cambio modo...)
|
||||
# gateway -> dmr/nxdn/ysf/p25/dstar-gateway/<id>/json
|
||||
# health -> devices/<id>/services (heartbeat dell'agent sul nodo)
|
||||
START_TIME = time.time()
|
||||
last_seen = {}
|
||||
last_seen_lock = threading.Lock()
|
||||
@@ -266,13 +256,11 @@ def touch_seen(cid, kind):
|
||||
last_seen.setdefault(cid, {})[kind] = time.time()
|
||||
|
||||
def seen_ages():
|
||||
"""Età (in secondi) dell'ultimo messaggio per nodo/tipo, calcolata sul server (niente problemi di orologio)."""
|
||||
now = time.time()
|
||||
with last_seen_lock:
|
||||
return {cid: {k: round(now - ts, 1) for k, ts in kinds.items()} for cid, kinds in last_seen.items()}
|
||||
|
||||
def seed_last_seen():
|
||||
"""Dopo un riavvio del server si riparte dall'ultimo evento radio registrato nel DB (dato reale)."""
|
||||
try:
|
||||
with closing(sqlite3.connect(DB_PATH, timeout=10)) as conn:
|
||||
rows = conn.execute("""SELECT LOWER(client_id), MAX(timestamp) FROM radio_logs
|
||||
@@ -297,21 +285,17 @@ def on_connect(client, userdata, flags, reason_code, properties=None):
|
||||
if reason_code == 0:
|
||||
mqtt_connected_status = True
|
||||
logger.info("✅ Successfully connected to MQTT Broker! Subscribing to topics...")
|
||||
# Invia lo stato Online ai client web
|
||||
socketio.emit('mqtt_status', {'connected': True})
|
||||
|
||||
# --- LETTURA DINAMICA DEI TOPIC ---
|
||||
default_topics = [
|
||||
"servizi/+/stat", "dmr-gateway/+/json", "devices/+/services",
|
||||
"nxdn-gateway/+/json", "ysf-gateway/+/json", "p25-gateway/+/json",
|
||||
"dstar-gateway/+/json", "mmdvm/+/json", "data/#"
|
||||
]
|
||||
|
||||
# Cerca la lista "topics" nel config.json, se non la trova usa quella di default
|
||||
topics_list = config.get('mqtt', {}).get('topics', default_topics)
|
||||
|
||||
# Converte la lista di stringhe nel formato richiesto da paho-mqtt: [(topic, qos), (topic, qos)...]
|
||||
subscribe_list = [(topic, 0) for topic in topics_list]
|
||||
subscribe_list.append(("+/+/log", 0)) # Ascolto dinamico dei log
|
||||
|
||||
client.subscribe(subscribe_list)
|
||||
logger.info(f"Subscribed to {len(subscribe_list)} MQTT topics.")
|
||||
@@ -323,11 +307,9 @@ def on_connect(client, userdata, flags, reason_code, properties=None):
|
||||
def on_disconnect(client, userdata, disconnect_flags, reason_code, properties=None):
|
||||
global mqtt_connected_status
|
||||
mqtt_connected_status = False
|
||||
# Invia lo stato Offline ai client web
|
||||
socketio.emit('mqtt_status', {'connected': False})
|
||||
logger.warning(f"⚠️ MQTT Disconnection detected! Reason code: {reason_code}. Attempting automatic reconnection...")
|
||||
|
||||
# Quando un nuovo utente apre la pagina web, inviagli subito lo stato attuale
|
||||
@socketio.on('connect')
|
||||
def handle_connect():
|
||||
emit('mqtt_status', {'connected': mqtt_connected_status})
|
||||
@@ -340,14 +322,51 @@ def on_message(client, userdata, msg):
|
||||
if len(parts) < 2: return
|
||||
|
||||
cid = parts[1].lower()
|
||||
|
||||
# --- MAGIA DELLA NORMALIZZAZIONE ---
|
||||
# Prendiamo i blocchi del topic, li facciamo minuscoli e togliamo i trattini
|
||||
# Così "DMRGateway", "dmr-gateway" e "dmrgateway" diventano tutti identici per noi
|
||||
p0 = parts[0].lower().replace('-', '')
|
||||
p2 = parts[2].lower().replace('-', '') if len(parts) > 2 else ""
|
||||
|
||||
# --- DIAGNOSTICA: registra l'arrivo dell'ultimo messaggio per tipo ---
|
||||
# --- LOG MANAGEMENT (ESTRAZIONE VERSIONI E GIT ID) ---
|
||||
if len(parts) >= 3 and parts[2].lower() == 'log':
|
||||
if cid not in node_versions:
|
||||
node_versions[cid] = {}
|
||||
|
||||
# 1. Cattura il Firmware MMDVM (es. "... description: MMDVM 20260424 19.2000 Mhz GitID #57e692a")
|
||||
m_fw = re.search(r'description:\s*(MMDVM[^\n\r]+)', payload, re.IGNORECASE)
|
||||
if m_fw:
|
||||
node_versions[cid]["Firmware MMDVM"] = m_fw.group(1).strip()
|
||||
notify_update()
|
||||
|
||||
# 2. Cattura le versioni dei demoni Formato A (es. "YSFGateway-20260323 is starting")
|
||||
m_sw1 = re.search(r'([A-Za-z0-9_]+)-([a-zA-Z0-9.\-]+)\s+is starting', payload, re.IGNORECASE)
|
||||
if m_sw1:
|
||||
prog = m_sw1.group(1)
|
||||
node_versions[cid][prog] = m_sw1.group(2).strip()
|
||||
node_versions[cid]["_last_prog"] = prog # Per il GitID della riga dopo
|
||||
notify_update()
|
||||
|
||||
# 3. Cattura le versioni dei demoni Formato B (es. "MMDVMHost version 20250419 git #65ebb55")
|
||||
m_sw2 = re.search(r'([A-Za-z0-9_]+)\s+version\s+([a-zA-Z0-9.\-\s#]+)', payload, re.IGNORECASE)
|
||||
if m_sw2:
|
||||
prog = m_sw2.group(1)
|
||||
# Ignoriamo i falsi positivi dei log (es. "protocol version", "firmware version")
|
||||
if prog.lower() not in ['protocol', 'firmware', 'mmdvm firmware']:
|
||||
# Puliamo un eventuale "is starting" finale, se presente
|
||||
ver = m_sw2.group(2).replace("is starting", "").strip()
|
||||
node_versions[cid][prog] = ver
|
||||
node_versions[cid]["_last_prog"] = prog
|
||||
notify_update()
|
||||
|
||||
# 4. Cattura il GitID della riga successiva per i demoni di Formato A
|
||||
m_git = re.search(r'Built .*?\(GitID #([0-9a-fA-F]+)\)', payload, re.IGNORECASE)
|
||||
if m_git:
|
||||
git_id = m_git.group(1)
|
||||
last_prog = node_versions[cid].get("_last_prog")
|
||||
if last_prog and last_prog in node_versions[cid]:
|
||||
if "GitID" not in node_versions[cid][last_prog]:
|
||||
node_versions[cid][last_prog] += f" (GitID #{git_id})"
|
||||
notify_update()
|
||||
return
|
||||
|
||||
if p0 == 'mmdvm':
|
||||
touch_seen(cid, 'mmdvm')
|
||||
elif p0 in ('dmrgateway', 'nxdngateway', 'ysfgateway', 'p25gateway', 'dstargateway'):
|
||||
@@ -355,7 +374,6 @@ def on_message(client, userdata, msg):
|
||||
elif p0 == 'devices' and p2 == 'services':
|
||||
touch_seen(cid, 'health')
|
||||
|
||||
# --- CAPTURE FULL CONFIGURATIONS ---
|
||||
if p0 == 'data' and len(parts) >= 4 and parts[3].lower() == 'full_config':
|
||||
cid_conf = parts[1].lower()
|
||||
svc_name = parts[2].lower()
|
||||
@@ -367,14 +385,10 @@ def on_message(client, userdata, msg):
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing config JSON: {e}")
|
||||
|
||||
# --- NODE AND SERVICE STATE MANAGEMENT ---
|
||||
elif p0 == 'servizi':
|
||||
client_states[cid] = payload
|
||||
notify_update() # <--- WEBSOCKET
|
||||
notify_update()
|
||||
|
||||
# --- PUSH TRIGGER: NODE STATE ---
|
||||
# L'agente invia "OFFLINE - <ID>" (anche come LWT) e "ONLINE - <profilo>": si confronta il PREFISSO.
|
||||
# I messaggi retained (già sul broker quando il server si avvia) non generano notifiche.
|
||||
state_up = payload.upper()
|
||||
if state_up.startswith('OFFLINE'):
|
||||
if not msg.retain and last_notified_errors.get(f"{cid}_NODE") != 'OFFLINE':
|
||||
@@ -391,7 +405,6 @@ def on_message(client, userdata, msg):
|
||||
client_telemetry[cid] = {"ts1": "Waiting...", "ts2": "Waiting...", "alt": ""}
|
||||
save_cache(client_telemetry)
|
||||
|
||||
# --- DEVICE HEALTH MANAGEMENT ---
|
||||
elif p0 == 'devices' and len(parts) >= 3 and p2 == 'services':
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
@@ -402,15 +415,32 @@ def on_message(client, userdata, msg):
|
||||
"disk": round(data.get("disk_usage_percent", 0), 1),
|
||||
"processes": data.get("processes", {}),
|
||||
"files": data.get("files", data.get("config_files", [])),
|
||||
"file_names": data.get("file_names", []),
|
||||
"profiles": data.get("profiles", {"A": "PROFILE A", "B": "PROFILE B"}),
|
||||
"interval": data.get("update_interval")
|
||||
}
|
||||
# --- AGGIUNTA E PULIZIA: SALVA LE VERSIONI DEI BINARI ---
|
||||
bin_versions = data.get("versions", {})
|
||||
if bin_versions:
|
||||
if cid not in node_versions:
|
||||
node_versions[cid] = {}
|
||||
|
||||
# Rimuove le vecchie versioni binarie che il nodo non trasmette più
|
||||
# (proteggendo però il "Firmware MMDVM" e le chiavi interne che derivano dai log)
|
||||
keys_to_remove = [k for k in node_versions[cid].keys()
|
||||
if k not in bin_versions and k not in ["Firmware MMDVM", "_last_prog"]]
|
||||
for k in keys_to_remove:
|
||||
del node_versions[cid][k]
|
||||
|
||||
# Aggiorna o aggiunge le versioni attuali
|
||||
for prog_name, prog_ver in bin_versions.items():
|
||||
node_versions[cid][prog_name] = prog_ver
|
||||
# ----------------------------------------------
|
||||
health_changed = device_health.get(cid) != new_health
|
||||
device_health[cid] = new_health
|
||||
if health_changed:
|
||||
notify_update() # <--- WEBSOCKET
|
||||
notify_update()
|
||||
|
||||
# --- PUSH TRIGGER: SERVICE ERRORS ---
|
||||
processes = data.get("processes", {})
|
||||
for svc_name, svc_status in processes.items():
|
||||
status_key = f"{cid}_{svc_name}"
|
||||
@@ -424,12 +454,10 @@ def on_message(client, userdata, msg):
|
||||
elif s_lower == "online" and status_key in last_notified_errors:
|
||||
broadcast_push_notification(f"✅ RESTORED: {cid.upper()}", f"Service {svc_name} back ONLINE.", cid=cid)
|
||||
del last_notified_errors[status_key]
|
||||
# -----------------------------------------
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing health data: {e}")
|
||||
|
||||
# --- DMR GATEWAY MANAGEMENT ---
|
||||
elif len(parts) >= 4 and p0 == 'data' and p2 == 'dmrgateway' and (parts[3].upper().startswith('NETWORK') or parts[3].upper().startswith('DMR NETWORK')):
|
||||
try:
|
||||
cid = parts[1].lower()
|
||||
@@ -451,18 +479,16 @@ def on_message(client, userdata, msg):
|
||||
|
||||
if is_ts1: network_mapping[cid]["ts1"] = net_name
|
||||
if is_ts2: network_mapping[cid]["ts2"] = net_name
|
||||
notify_update() # <--- WEBSOCKET
|
||||
notify_update()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing DMRGateway for {cid}: {e}")
|
||||
|
||||
# --- MMDVMHOST INFO MANAGEMENT (FREQUENZE & LOCATION) ---
|
||||
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost') and parts[3].lower() == 'info':
|
||||
try:
|
||||
cid = parts[1].lower()
|
||||
data = json.loads(payload)
|
||||
|
||||
# Estrazione dati
|
||||
tx = data.get("TXFrequency", "0")
|
||||
rx = data.get("RXFrequency", "0")
|
||||
lat = data.get("Latitude", "0.0")
|
||||
@@ -471,7 +497,12 @@ def on_message(client, userdata, msg):
|
||||
|
||||
def format_freq(f):
|
||||
if str(f).isdigit() and int(f) > 0:
|
||||
return f"{int(f)/1000000:.3f} MHz"
|
||||
hz = int(f)
|
||||
mhz, frac = divmod(hz, 1000000)
|
||||
dec = f"{frac:06d}"
|
||||
if dec.endswith("0"):
|
||||
dec = dec[:-1]
|
||||
return f"{mhz}.{dec} MHz"
|
||||
return str(f)
|
||||
|
||||
node_info[cid] = {
|
||||
@@ -485,14 +516,13 @@ def on_message(client, userdata, msg):
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing MMDVMHost info for {cid}: {e}")
|
||||
|
||||
# --- MMDVMHOST GENERAL MANAGEMENT (CALLSIGN & ID & DUPLEX) ---
|
||||
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost') and parts[3].lower() == 'general':
|
||||
try:
|
||||
cid = parts[1].lower()
|
||||
data = json.loads(payload)
|
||||
callsign = data.get("Callsign", "")
|
||||
radio_id = data.get("Id", "")
|
||||
duplex = data.get("Duplex", "1") # 1 = Repeater, 0 = Simplex
|
||||
duplex = data.get("Duplex", "1")
|
||||
|
||||
if callsign:
|
||||
node_general[cid] = {"callsign": callsign, "radio_id": radio_id, "duplex": str(duplex)}
|
||||
@@ -500,7 +530,6 @@ def on_message(client, userdata, msg):
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing MMDVMHost general for {cid}: {e}")
|
||||
|
||||
# --- OTHER GATEWAYS MANAGEMENT ---
|
||||
elif p0 in ['dmrgateway', 'nxdngateway', 'ysfgateway', 'p25gateway', 'dstargateway']:
|
||||
data = json.loads(payload)
|
||||
proto = "DMR"
|
||||
@@ -522,7 +551,6 @@ def on_message(client, userdata, msg):
|
||||
|
||||
if m: save_to_sqlite(cid, {'src_id': "🌐 " + m, 'dst_id': 'NET'}, protocol=proto)
|
||||
|
||||
# --- MMDVM AND TRAFFIC MANAGEMENT ---
|
||||
elif parts[0] == 'mmdvm':
|
||||
data = json.loads(payload)
|
||||
if cid not in active_calls: active_calls[cid] = {}
|
||||
@@ -546,7 +574,7 @@ def on_message(client, userdata, msg):
|
||||
active_calls[cid][sk] = {'src': src, 'dst': dst}
|
||||
client_telemetry[cid]["alt"] = ""
|
||||
client_telemetry[cid][sk] = f"🎙️ {src} ➔ TG {dst}"
|
||||
notify_update() # <--- WEBSOCKET
|
||||
notify_update()
|
||||
elif act in ['end', 'lost']:
|
||||
info = active_calls[cid].get(sk, {'src': '---', 'dst': '---'})
|
||||
d['src_id'], d['dst_id'] = info['src'], info['dst']
|
||||
@@ -576,7 +604,7 @@ def on_message(client, userdata, msg):
|
||||
|
||||
active_calls[cid][k] = {'src': src, 'dst': target, 'ext': str(p.get('src_ext', ''))}
|
||||
client_telemetry[cid].update({"ts1":"","ts2":"","alt": f"{ico} {name}: {src} ➔ {target}"})
|
||||
notify_update() # <--- WEBSOCKET
|
||||
notify_update()
|
||||
|
||||
elif act in ['end', 'lost']:
|
||||
info = active_calls[cid].get(k, {'src': '---', 'dst': '---', 'ext': ''})
|
||||
@@ -588,17 +616,13 @@ def on_message(client, userdata, msg):
|
||||
except Exception as e:
|
||||
logger.error(f"MQTT MSG ERROR: {e}")
|
||||
|
||||
# --- MQTT CLIENT INITIALIZATION ---
|
||||
# Recuperiamo l'ID dal config. Se per caso manca, usiamo un default di emergenza.
|
||||
mqtt_id = config['mqtt'].get('client_id', 'flask_backend_generic')
|
||||
|
||||
mqtt_backend = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, mqtt_id)
|
||||
mqtt_backend.username_pw_set(config['mqtt']['user'], config['mqtt']['password'])
|
||||
mqtt_backend.on_connect = on_connect
|
||||
mqtt_backend.on_disconnect = on_disconnect
|
||||
mqtt_backend.on_message = on_message
|
||||
try:
|
||||
# Usiamo connect_async! Non blocca il server se l'IP è irraggiungibile
|
||||
mqtt_backend.connect_async(config['mqtt']['broker'], config['mqtt']['port'])
|
||||
mqtt_backend.loop_start()
|
||||
logger.info(f"Avvio connessione MQTT asincrona verso {config['mqtt']['broker']}...")
|
||||
@@ -606,7 +630,6 @@ except Exception as e:
|
||||
logger.error(f"Errore critico nell'inizializzazione MQTT: {e}")
|
||||
|
||||
def mqtt_publish(topic, payload, qos=1):
|
||||
"""Pubblica solo se il broker è raggiungibile (niente comandi 'vecchi' accodati e consegnati dopo)."""
|
||||
if not mqtt_connected_status:
|
||||
logger.warning(f"MQTT offline: pubblicazione su {topic} annullata")
|
||||
return False
|
||||
@@ -649,6 +672,11 @@ def get_logs():
|
||||
|
||||
@app.route('/api/states', methods=['GET'])
|
||||
def get_states():
|
||||
# Filtriamo le chiavi di servizio (come '_last_prog') per non mandarle all'interfaccia
|
||||
clean_versions = {}
|
||||
for c, d in node_versions.items():
|
||||
clean_versions[c] = {k: v for k, v in d.items() if not k.startswith('_')}
|
||||
|
||||
return jsonify({
|
||||
"states": client_states,
|
||||
"telemetry": client_telemetry,
|
||||
@@ -657,46 +685,41 @@ def get_states():
|
||||
"info": node_info,
|
||||
"general": node_general,
|
||||
"last_seen": seen_ages(),
|
||||
"uptime": int(time.time() - START_TIME)
|
||||
"uptime": int(time.time() - START_TIME),
|
||||
"versions": clean_versions
|
||||
})
|
||||
|
||||
@app.route('/api/stats')
|
||||
def get_stats():
|
||||
# Leggiamo il parametro 'node' (di default 'all')
|
||||
node = request.args.get('node', 'all').lower()
|
||||
|
||||
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||
c = conn.cursor()
|
||||
|
||||
# Prepariamo il filtro aggiuntivo se è stato selezionato un nodo
|
||||
node_filter = ""
|
||||
params = []
|
||||
if node != 'all':
|
||||
node_filter = " AND LOWER(client_id) = ?"
|
||||
params.append(node)
|
||||
|
||||
# 1. Top 5 TalkGroups di OGGI
|
||||
c.execute(f"""SELECT target, COUNT(*) as cnt FROM radio_logs
|
||||
WHERE target NOT IN ('---', 'NET', '')
|
||||
AND timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter}
|
||||
GROUP BY target ORDER BY cnt DESC LIMIT 5""", params)
|
||||
top_tgs = [{"target": row[0], "count": row[1]} for row in c.fetchall()]
|
||||
|
||||
# 2. Top 5 Callsign di OGGI
|
||||
c.execute(f"""SELECT source_id, COUNT(*) as cnt FROM radio_logs
|
||||
WHERE source_id NOT LIKE '🌐%'
|
||||
AND timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter}
|
||||
GROUP BY source_id ORDER BY cnt DESC LIMIT 5""", params)
|
||||
top_calls = [{"call": row[0], "count": row[1]} for row in c.fetchall()]
|
||||
|
||||
# 3. Tempo medio dei transiti di OGGI
|
||||
c.execute(f"""SELECT AVG(duration) FROM radio_logs
|
||||
WHERE duration > 0.5
|
||||
AND timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter}""", params)
|
||||
avg_dur = c.fetchone()[0]
|
||||
avg_dur = round(avg_dur, 1) if avg_dur else 0
|
||||
|
||||
# 4. Totale transiti di OGGI
|
||||
c.execute(f"SELECT COUNT(*) FROM radio_logs WHERE timestamp >= date('now', 'localtime') AND timestamp < date('now', 'localtime', '+1 day'){node_filter}", params)
|
||||
today_tx = c.fetchone()[0]
|
||||
|
||||
@@ -719,35 +742,27 @@ PROFILE_KEY_RE = re.compile(r'^[A-Za-z0-9_\-]{1,32}$')
|
||||
TIME_RE = re.compile(r'^([01]\d|2[0-3]):[0-5]\d$')
|
||||
MIN_PASSWORD_LEN = 8
|
||||
|
||||
# Comandi inviabili a un nodo (topic servizi/<id>/cmnd)
|
||||
SIMPLE_COMMANDS = {'TG:ON', 'TG:OFF'}
|
||||
PRIVILEGED_COMMANDS = {'REBOOT', 'RESET_HAT', 'UPDATE_AGENT'} # solo admin
|
||||
PRIVILEGED_COMMANDS = {'REBOOT', 'RESET_HAT', 'UPDATE_AGENT'}
|
||||
SERVICE_ACTIONS = {'start', 'stop', 'restart'}
|
||||
|
||||
|
||||
def db_connect(row=False):
|
||||
conn = sqlite3.connect(DB_PATH, timeout=10)
|
||||
if row:
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def json_body():
|
||||
d = request.get_json(silent=True)
|
||||
return d if isinstance(d, dict) else {}
|
||||
|
||||
|
||||
def err(msg, code=400):
|
||||
return jsonify({"success": False, "error": msg}), code
|
||||
|
||||
|
||||
def pw_fingerprint(password_hash):
|
||||
"""Impronta dell'hash: cambiando password le vecchie sessioni diventano invalide."""
|
||||
return hashlib.sha256(password_hash.encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def get_auth():
|
||||
"""Utente della sessione, riletto dal DB a ogni richiesta (ruolo/nodi sempre aggiornati)."""
|
||||
username = session.get('user')
|
||||
if not session.get('logged_in') or not username:
|
||||
return None
|
||||
@@ -755,11 +770,10 @@ def get_auth():
|
||||
row = conn.execute("SELECT username, password_hash, role, allowed_nodes FROM users WHERE username = ?",
|
||||
(username,)).fetchone()
|
||||
if not row or session.get('pv') != pw_fingerprint(row['password_hash']):
|
||||
session.clear() # utente cancellato o password cambiata
|
||||
session.clear()
|
||||
return None
|
||||
return {"username": row['username'], "role": row['role'], "allowed_nodes": row['allowed_nodes'] or ''}
|
||||
|
||||
|
||||
def node_allowed(role, allowed_nodes, cid):
|
||||
if role == 'admin':
|
||||
return True
|
||||
@@ -768,9 +782,7 @@ def node_allowed(role, allowed_nodes, cid):
|
||||
return True
|
||||
return cid in [x.strip().lower() for x in allowed.split(',') if x.strip()]
|
||||
|
||||
|
||||
def known_profile_keys(cid=None):
|
||||
"""Chiavi di profilo valide (A/B + quelle annunciate dai nodi)."""
|
||||
keys = {'A', 'B'}
|
||||
healths = [device_health.get(cid)] if cid else list(device_health.values())
|
||||
for h in healths:
|
||||
@@ -779,7 +791,6 @@ def known_profile_keys(cid=None):
|
||||
keys.update(str(k) for k in profiles.keys() if PROFILE_KEY_RE.match(str(k)))
|
||||
return keys - PRIVILEGED_COMMANDS - SIMPLE_COMMANDS
|
||||
|
||||
|
||||
def audit(username, client_id, command):
|
||||
try:
|
||||
with closing(db_connect()) as conn:
|
||||
@@ -789,7 +800,6 @@ def audit(username, client_id, command):
|
||||
except Exception as e:
|
||||
logger.error(f"Audit log error: {e}")
|
||||
|
||||
|
||||
def count_admins(cursor, exclude_id=None):
|
||||
if exclude_id is None:
|
||||
cursor.execute("SELECT COUNT(*) FROM users WHERE role = 'admin'")
|
||||
@@ -797,30 +807,24 @@ def count_admins(cursor, exclude_id=None):
|
||||
cursor.execute("SELECT COUNT(*) FROM users WHERE role = 'admin' AND id != ?", (exclude_id,))
|
||||
return cursor.fetchone()[0]
|
||||
|
||||
|
||||
def normalize_nodes(value):
|
||||
value = (value or '').strip().lower()
|
||||
if not value or value == 'all':
|
||||
return 'all'
|
||||
return ','.join(x.strip() for x in value.split(',') if x.strip())
|
||||
|
||||
|
||||
# --- Limitazione tentativi di login (per IP, in memoria) ---
|
||||
LOGIN_MAX_FAILS = 5
|
||||
LOGIN_WINDOW_SEC = 300
|
||||
login_attempts = {}
|
||||
login_lock = threading.Lock()
|
||||
|
||||
|
||||
def client_ip():
|
||||
# X-Forwarded-For si fida solo se esplicitamente abilitato ("web": {"trust_proxy": true})
|
||||
if config.get('web', {}).get('trust_proxy'):
|
||||
fwd = request.headers.get('X-Forwarded-For', '')
|
||||
if fwd:
|
||||
return fwd.split(',')[0].strip()
|
||||
return request.remote_addr or 'unknown'
|
||||
|
||||
|
||||
def login_blocked(ip):
|
||||
now = time.time()
|
||||
with login_lock:
|
||||
@@ -831,20 +835,14 @@ def login_blocked(ip):
|
||||
login_attempts.pop(ip, None)
|
||||
return len(fails) >= LOGIN_MAX_FAILS
|
||||
|
||||
|
||||
def login_register_fail(ip):
|
||||
with login_lock:
|
||||
login_attempts.setdefault(ip, []).append(time.time())
|
||||
|
||||
|
||||
def login_reset(ip):
|
||||
with login_lock:
|
||||
login_attempts.pop(ip, None)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# ROUTE: SESSIONE
|
||||
# =====================================================================
|
||||
@app.route('/api/login', methods=['POST'])
|
||||
def login():
|
||||
d = json_body()
|
||||
@@ -874,13 +872,11 @@ def login():
|
||||
logger.warning(f"Login fallito per {username[:32]!r} da {ip}")
|
||||
return jsonify({"success": False}), 401
|
||||
|
||||
|
||||
@app.route('/api/logout', methods=['POST'])
|
||||
def logout():
|
||||
session.clear()
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
@app.route('/api/me')
|
||||
def me():
|
||||
auth = get_auth()
|
||||
@@ -889,10 +885,6 @@ def me():
|
||||
return jsonify({"logged_in": True, "user": auth['username'], "role": auth['role'],
|
||||
"allowed_nodes": auth['allowed_nodes']})
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# ROUTE: COMANDI AI NODI
|
||||
# =====================================================================
|
||||
@app.route('/api/command', methods=['POST'])
|
||||
def cmd():
|
||||
auth = get_auth()
|
||||
@@ -926,7 +918,6 @@ def cmd():
|
||||
client_telemetry[cid] = {"ts1": "🔄 Sent...", "ts2": "🔄 Sent...", "alt": ""}
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
@app.route('/api/global_command', methods=['POST'])
|
||||
def global_cmd():
|
||||
auth = get_auth()
|
||||
@@ -956,7 +947,6 @@ def global_cmd():
|
||||
return err("MQTT broker offline - command not sent", 503)
|
||||
return jsonify({"success": True, "sent": sent, "failed": failed})
|
||||
|
||||
|
||||
@app.route('/api/service_control', methods=['POST'])
|
||||
def service_control():
|
||||
auth = get_auth()
|
||||
@@ -979,7 +969,6 @@ def service_control():
|
||||
audit(auth['username'], cid, f"SVC_{action.upper()}_{service}")
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
@app.route('/api/update_nodes', methods=['POST'])
|
||||
def update_nodes():
|
||||
auth = get_auth()
|
||||
@@ -991,10 +980,6 @@ def update_nodes():
|
||||
audit(auth['username'], '*', 'REQ_CONFIG_ALL')
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# ROUTE: UTENTI
|
||||
# =====================================================================
|
||||
@app.route('/api/users', methods=['GET'])
|
||||
def get_users():
|
||||
auth = get_auth()
|
||||
@@ -1004,7 +989,6 @@ def get_users():
|
||||
users = [dict(r) for r in conn.execute("SELECT id, username, role, allowed_nodes FROM users")]
|
||||
return jsonify(users)
|
||||
|
||||
|
||||
@app.route('/api/users', methods=['POST'])
|
||||
def add_user():
|
||||
auth = get_auth()
|
||||
@@ -1036,7 +1020,6 @@ def add_user():
|
||||
audit(auth['username'], '-', f"USER_ADD_{username}_{role}")
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
@app.route('/api/users/<int:user_id>', methods=['DELETE'])
|
||||
def delete_user(user_id):
|
||||
auth = get_auth()
|
||||
@@ -1059,7 +1042,6 @@ def delete_user(user_id):
|
||||
audit(auth['username'], '-', f"USER_DEL_{u[0]}")
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
@app.route('/api/users/<int:user_id>', methods=['PUT'])
|
||||
def update_user(user_id):
|
||||
auth = get_auth()
|
||||
@@ -1096,7 +1078,6 @@ def update_user(user_id):
|
||||
audit(auth['username'], '-', f"USER_EDIT_{existing[0]}")
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
@app.route('/api/change_password', methods=['POST'])
|
||||
def change_password():
|
||||
auth = get_auth()
|
||||
@@ -1122,12 +1103,7 @@ def change_password():
|
||||
audit(auth['username'], '-', f"PASSWORD_CHANGE_{user_to_change}")
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# AGGIORNAMENTO DATABASE ID + PULIZIA DB
|
||||
# =====================================================================
|
||||
def download_file(url, dest):
|
||||
"""Scarica in un file temporaneo e sostituisce l'originale solo a download riuscito."""
|
||||
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
with urllib.request.urlopen(req, timeout=60) as response:
|
||||
@@ -1139,9 +1115,7 @@ def download_file(url, dest):
|
||||
out_file.write(data)
|
||||
os.replace(tmp, dest)
|
||||
|
||||
|
||||
def prune_old_data():
|
||||
"""Retention: radio_logs (default 90 gg) e audit_logs (default 365 gg)."""
|
||||
try:
|
||||
cfg = read_config()
|
||||
radio_days = int(cfg.get("retention_days", 90))
|
||||
@@ -1158,10 +1132,7 @@ def prune_old_data():
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Errore pulizia DB: {e}")
|
||||
|
||||
|
||||
def auto_update_ids():
|
||||
"""Controlla all'avvio e poi ogni notte all'orario configurato."""
|
||||
|
||||
def download_logic():
|
||||
try:
|
||||
urls = read_config().get("id_urls") or {}
|
||||
@@ -1193,10 +1164,6 @@ def auto_update_ids():
|
||||
logger.error(f"⚠️ Errore nel thread update: {e}")
|
||||
time.sleep(30)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# ROUTE: CONFIGURAZIONE
|
||||
# =====================================================================
|
||||
@app.route('/api/ui_config', methods=['GET'])
|
||||
def get_ui_config():
|
||||
try:
|
||||
@@ -1212,7 +1179,6 @@ def get_ui_config():
|
||||
logger.error(f"ui_config error: {e}")
|
||||
return jsonify({"error": "Configuration unavailable"}), 500
|
||||
|
||||
|
||||
@app.route('/api/config', methods=['GET'])
|
||||
def get_config_api():
|
||||
auth = get_auth()
|
||||
@@ -1225,7 +1191,6 @@ def get_config_api():
|
||||
"url_nxdn": cfg.get("id_urls", {}).get("nxdn", "")
|
||||
})
|
||||
|
||||
|
||||
@app.route('/api/config', methods=['POST'])
|
||||
def save_config_api():
|
||||
auth = get_auth()
|
||||
@@ -1251,7 +1216,6 @@ def save_config_api():
|
||||
audit(auth['username'], '-', 'EDIT_SERVER_CONFIG')
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
@app.route('/api/config_file/<cid>/<service>', methods=['GET'])
|
||||
def get_config_file(cid, service):
|
||||
auth = get_auth()
|
||||
@@ -1266,7 +1230,6 @@ def get_config_file(cid, service):
|
||||
return err("Configuration not received yet. Wait or send an UPDATE command.", 404)
|
||||
return jsonify({"success": True, "data": config_data})
|
||||
|
||||
|
||||
@app.route('/api/config_file', methods=['POST'])
|
||||
def save_config_file():
|
||||
auth = get_auth()
|
||||
@@ -1289,34 +1252,23 @@ def save_config_file():
|
||||
audit(auth['username'], cid, f"EDIT_CONFIG_{service.upper()}")
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# PWA: MANIFEST / SERVICE WORKER / ICONA
|
||||
# =====================================================================
|
||||
@app.route('/manifest.json')
|
||||
def serve_manifest():
|
||||
return send_from_directory(BASE_DIR, 'manifest.json')
|
||||
|
||||
|
||||
@app.route('/sw.js')
|
||||
def serve_sw():
|
||||
resp = send_from_directory(BASE_DIR, 'sw.js', mimetype='application/javascript')
|
||||
resp.headers['Cache-Control'] = 'no-cache' # il browser controlla sempre se il SW è cambiato
|
||||
resp.headers['Cache-Control'] = 'no-cache'
|
||||
resp.headers['Service-Worker-Allowed'] = '/'
|
||||
return resp
|
||||
|
||||
|
||||
@app.route('/icon-512.png')
|
||||
def serve_icon():
|
||||
return send_from_directory(BASE_DIR, 'icon-512.png')
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# PUSH NOTIFICATIONS (invio in un thread dedicato: non blocca MQTT)
|
||||
# =====================================================================
|
||||
push_queue = queue.Queue(maxsize=200)
|
||||
|
||||
|
||||
def broadcast_push_notification(title, body, cid=None):
|
||||
if not config.get('webpush'):
|
||||
return
|
||||
@@ -1325,7 +1277,6 @@ def broadcast_push_notification(title, body, cid=None):
|
||||
except queue.Full:
|
||||
logger.warning("Push queue piena: notifica scartata")
|
||||
|
||||
|
||||
def _send_push(title, body, cid):
|
||||
wp_config = config.get('webpush')
|
||||
if not wp_config:
|
||||
@@ -1338,11 +1289,11 @@ def _send_push(title, body, cid):
|
||||
FROM push_subscriptions p
|
||||
LEFT JOIN users u ON u.username = p.username""").fetchall()
|
||||
for sub_id, sub_json, role, allowed in rows:
|
||||
if role is None: # utente cancellato
|
||||
if role is None:
|
||||
dead.append(sub_id)
|
||||
continue
|
||||
if cid and not node_allowed(role, allowed, cid):
|
||||
continue # l'operatore non gestisce questo nodo
|
||||
continue
|
||||
try:
|
||||
webpush(
|
||||
subscription_info=json.loads(sub_json),
|
||||
@@ -1364,7 +1315,6 @@ def _send_push(title, body, cid):
|
||||
if dead:
|
||||
conn.commit()
|
||||
|
||||
|
||||
def push_worker():
|
||||
while True:
|
||||
title, body, cid = push_queue.get()
|
||||
@@ -1373,12 +1323,10 @@ def push_worker():
|
||||
except Exception as e:
|
||||
logger.error(f"Push worker error: {e}")
|
||||
|
||||
|
||||
@app.route('/api/vapid_public_key')
|
||||
def get_vapid_key():
|
||||
return jsonify({"public_key": config.get('webpush', {}).get('vapid_public_key', '')})
|
||||
|
||||
|
||||
@app.route('/api/subscribe', methods=['POST'])
|
||||
def subscribe_push():
|
||||
auth = get_auth()
|
||||
@@ -1388,17 +1336,14 @@ def subscribe_push():
|
||||
if not sub_data.get('endpoint'):
|
||||
return err("Invalid subscription")
|
||||
with closing(db_connect()) as conn:
|
||||
# Se lo stesso browser si iscrive con un altro utente, la subscription passa al nuovo utente
|
||||
conn.execute("""INSERT INTO push_subscriptions (username, subscription) VALUES (?, ?)
|
||||
ON CONFLICT(subscription) DO UPDATE SET username = excluded.username""",
|
||||
(auth['username'], json.dumps(sub_data)))
|
||||
conn.commit()
|
||||
return jsonify({"success": True})
|
||||
|
||||
|
||||
threading.Thread(target=auto_update_ids, daemon=True).start()
|
||||
threading.Thread(target=push_worker, daemon=True).start()
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Eseguire con UN SOLO processo: client MQTT, thread e cache sono in memoria.
|
||||
socketio.run(app, host='0.0.0.0', port=9000)
|
||||
|
||||
+202
-101
@@ -28,10 +28,25 @@
|
||||
body { font-family: 'Inter', sans-serif; background: var(--bg-gradient); margin: 0; padding: 0; color: var(--text-main); min-height: 100vh; }
|
||||
|
||||
/* Barra superiore squadrata e tecnica */
|
||||
#top-bar-container { position: sticky; top: 15px; z-index: 100; padding: 0 20px; display: flex; justify-content: center; }
|
||||
#top-bar-container {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
padding: 15px 20px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
background: var(--bg-gradient);
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
#top-bar { background: var(--topbar-bg); padding: 12px 30px; display: flex; justify-content: space-between; align-items: center; border-radius: 6px; border: 1px solid var(--border-color); width: 100%; max-width: 1400px; }
|
||||
.title-brand { font-size: 1.2rem; font-weight: 800; letter-spacing: 2px; color: var(--text-main); font-family: 'JetBrains Mono', monospace; }
|
||||
|
||||
/* --- Navigation Tabs --- */
|
||||
.nav-tabs { display: flex; gap: 15px; margin-left: 30px; flex: 1; }
|
||||
.nav-tab { background: transparent; border: none; color: var(--text-muted); font-size: 0.95rem; font-weight: 800; cursor: pointer; padding: 6px 12px; border-bottom: 3px solid transparent; transition: all 0.2s ease; font-family: 'JetBrains Mono', monospace; letter-spacing: 1px; }
|
||||
.nav-tab:hover { color: var(--text-main); }
|
||||
.nav-tab.active { color: var(--primary); border-bottom: 3px solid var(--primary); }
|
||||
|
||||
.theme-switch { background: transparent; border: 1px solid var(--border-color); color: var(--text-muted); padding: 6px 14px; border-radius: 4px; cursor: pointer; font-weight: 600; font-size: 0.85rem; font-family: 'JetBrains Mono', monospace; }
|
||||
.theme-switch:hover { color: var(--text-main); border-color: var(--text-main); }
|
||||
|
||||
@@ -137,6 +152,7 @@
|
||||
#top-bar-container { top: 10px; padding: 0 10px; }
|
||||
#top-bar { flex-direction: column; padding: 15px; gap: 12px; border-radius: 8px; }
|
||||
.title-brand { font-size: 1.1rem; text-align: center; width: 100%; }
|
||||
.nav-tabs { margin-left: 0; width: 100%; justify-content: center; border-bottom: 1px solid var(--border-color); padding-bottom: 10px; margin-bottom: 10px; }
|
||||
#top-bar > div { width: 100%; flex-wrap: wrap; justify-content: center; gap: 8px !important; }
|
||||
#auth-container { width: 100%; justify-content: center; flex-wrap: wrap; padding-top: 12px; border-top: 1px solid var(--border-color); }
|
||||
#auth-container > span { width: 100%; text-align: center; margin-bottom: 8px; font-family: 'JetBrains Mono', monospace; }
|
||||
@@ -153,6 +169,13 @@
|
||||
<div id="top-bar-container">
|
||||
<div id="top-bar">
|
||||
<div class="title-brand">FLEET CONTROL CONSOLE</div>
|
||||
|
||||
<!-- Menu a schede -->
|
||||
<div class="nav-tabs">
|
||||
<button class="nav-tab active" onclick="switchView('home')" id="tab-home">HOME</button>
|
||||
<button class="nav-tab" onclick="switchView('nodes')" id="tab-nodes">NODES</button>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; align-items: center; gap: 12px;">
|
||||
<span id="mqtt-badge" class="mqtt-badge mqtt-offline">MQTT: CHECKING...</span>
|
||||
<button class="theme-switch" id="lang-btn" onclick="toggleLang()" data-i18n-title="ttLang">🇮🇹 ITA</button>
|
||||
@@ -162,62 +185,68 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid" id="client-grid"></div>
|
||||
|
||||
<div style="max-width: 1400px; margin: 0 auto 15px auto; padding: 0 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
|
||||
<h3 style="margin: 0; font-weight: 800; display: flex; align-items: center; gap: 10px; color: var(--text-main);">
|
||||
<span style="font-size: 1.5rem;">📊</span> <span data-i18n="statTitle">DAILY STATISTICS</span>
|
||||
</h3>
|
||||
<select id="stat-node-filter" onchange="refreshStats()" style="background: var(--card-bg); border: 1px solid var(--border-color); color: var(--text-main); padding: 8px 15px; border-radius: 6px; font-family: 'JetBrains Mono', monospace; font-weight: bold; cursor: pointer; outline: none;">
|
||||
<option value="all">🌐 ALL NODES</option>
|
||||
</select>
|
||||
<!-- ================= VISTA NODI ================= -->
|
||||
<div id="view-nodes" style="display: none;">
|
||||
<div class="grid" id="client-grid"></div>
|
||||
</div>
|
||||
|
||||
<div style="max-width: 1400px; margin: 0 auto 30px auto; padding: 0 20px; display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
|
||||
<div class="card" style="padding: 15px; border-top-color: var(--accent) !important;">
|
||||
<h4 style="margin: 0 0 10px 0; color: var(--accent); font-family: 'JetBrains Mono', monospace;" data-i18n="statTopTG">🎯 TOP TALKGROUPS</h4>
|
||||
<div id="stat-tgs" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading">Loading...</div>
|
||||
<!-- ================= VISTA HOME ================= -->
|
||||
<div id="view-home">
|
||||
<div style="max-width: 1400px; margin: 0 auto 15px auto; padding: 0 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">
|
||||
<h3 style="margin: 0; font-weight: 800; display: flex; align-items: center; gap: 10px; color: var(--text-main);">
|
||||
<span style="font-size: 1.5rem;">📊</span> <span data-i18n="statTitle">DAILY STATISTICS</span>
|
||||
</h3>
|
||||
<select id="stat-node-filter" onchange="refreshStats()" style="background: var(--card-bg); border: 1px solid var(--border-color); color: var(--text-main); padding: 8px 15px; border-radius: 6px; font-family: 'JetBrains Mono', monospace; font-weight: bold; cursor: pointer; outline: none;">
|
||||
<option value="all">🌐 ALL NODES</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="card" style="padding: 15px; border-top-color: var(--success) !important;">
|
||||
<h4 style="margin: 0 0 10px 0; color: var(--success); font-family: 'JetBrains Mono', monospace;" data-i18n="statTopCall">🗣️ TOP CALLSIGNS</h4>
|
||||
<div id="stat-calls" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading">Loading...</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="padding: 15px; border-top-color: var(--primary) !important; display: flex; justify-content: space-around; align-items: center; text-align: center;">
|
||||
<div>
|
||||
<div style="font-size: 1.8rem; font-weight: 800; color: var(--text-main); font-family: 'JetBrains Mono', monospace;"><span id="stat-avg">--</span>s</div>
|
||||
<div style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: bold;" data-i18n="statAvgDur">⏱️ AVERAGE DURATION</div>
|
||||
<div style="max-width: 1400px; margin: 0 auto 30px auto; padding: 0 20px; display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
|
||||
<div class="card" style="padding: 15px; border-top-color: var(--accent) !important;">
|
||||
<h4 style="margin: 0 0 10px 0; color: var(--accent); font-family: 'JetBrains Mono', monospace;" data-i18n="statTopTG">🎯 TOP TALKGROUPS</h4>
|
||||
<div id="stat-tgs" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading">Loading...</div>
|
||||
</div>
|
||||
<div style="width: 1px; height: 50px; background: var(--border-color);"></div>
|
||||
<div>
|
||||
<div style="font-size: 1.8rem; font-weight: 800; color: var(--text-main); font-family: 'JetBrains Mono', monospace;"><span id="stat-today">--</span></div>
|
||||
<div style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: bold;" data-i18n="statTodayTx">📡 TRANSITS TODAY</div>
|
||||
|
||||
<div class="card" style="padding: 15px; border-top-color: var(--success) !important;">
|
||||
<h4 style="margin: 0 0 10px 0; color: var(--success); font-family: 'JetBrains Mono', monospace;" data-i18n="statTopCall">🗣️ TOP CALLSIGNS</h4>
|
||||
<div id="stat-calls" style="font-size: 0.85rem; color: var(--text-muted); line-height: 1.8;" data-i18n="statLoading">Loading...</div>
|
||||
</div>
|
||||
|
||||
<div class="card" style="padding: 15px; border-top-color: var(--primary) !important; display: flex; justify-content: space-around; align-items: center; text-align: center;">
|
||||
<div>
|
||||
<div style="font-size: 1.8rem; font-weight: 800; color: var(--text-main); font-family: 'JetBrains Mono', monospace;"><span id="stat-avg">--</span>s</div>
|
||||
<div style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: bold;" data-i18n="statAvgDur">⏱️ AVERAGE DURATION</div>
|
||||
</div>
|
||||
<div style="width: 1px; height: 50px; background: var(--border-color);"></div>
|
||||
<div>
|
||||
<div style="font-size: 1.8rem; font-weight: 800; color: var(--text-main); font-family: 'JetBrains Mono', monospace;"><span id="stat-today">--</span></div>
|
||||
<div style="font-size: 0.75rem; color: var(--text-muted); text-transform: uppercase; font-weight: bold;" data-i18n="statTodayTx">📡 TRANSITS TODAY</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style="max-width: 1400px; margin: 0 auto;">
|
||||
<h3 style="margin-left: 20px; font-weight: 800; display: flex; align-items: center; gap: 10px; color: var(--text-main);">
|
||||
<span style="font-size: 1.5rem;">📡</span> <span data-i18n="lastTransits">Lastheard</span>
|
||||
</h3>
|
||||
<div class="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="thTime">Time</th>
|
||||
<th data-i18n="thRep">Repeater</th>
|
||||
<th data-i18n="thMode">Mode</th>
|
||||
<th style="text-align: center;">Slot</th>
|
||||
<th data-i18n="thCall">Callsign</th>
|
||||
<th>Target / TG</th>
|
||||
<th data-i18n="thDur">Duration</th>
|
||||
<th>BER</th>
|
||||
<th>RSSI</th> <!-- NUOVA COLONNA -->
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="log-body"></tbody>
|
||||
</table>
|
||||
<div style="max-width: 1400px; margin: 0 auto;">
|
||||
<h3 style="margin-left: 20px; font-weight: 800; display: flex; align-items: center; gap: 10px; color: var(--text-main);">
|
||||
<span style="font-size: 1.5rem;">📡</span> <span data-i18n="lastTransits">Lastheard</span>
|
||||
</h3>
|
||||
<div class="table-container">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="thTime">Time</th>
|
||||
<th data-i18n="thRep">Repeater</th>
|
||||
<th data-i18n="thMode">Mode</th>
|
||||
<th style="text-align: center;">Slot</th>
|
||||
<th data-i18n="thCall">Callsign</th>
|
||||
<th>Target / TG</th>
|
||||
<th data-i18n="thDur">Duration</th>
|
||||
<th>BER</th>
|
||||
<th>RSSI</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="log-body"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -391,6 +420,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- NUOVO MODALE VERSIONI -->
|
||||
<div id="versions-modal" class="modal-overlay">
|
||||
<div class="modal-content" style="width:90%; max-width:450px;">
|
||||
<div style="display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid var(--border-color); padding-bottom:15px; margin-bottom:15px;">
|
||||
<h2 style="margin:0; color:var(--primary);">ℹ️ <span data-i18n="modVersions">Software & Firmware</span></h2>
|
||||
<button onclick="closeVersionsModal()" style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:var(--danger);">✖</button>
|
||||
</div>
|
||||
<div id="versions-list" style="background: #010409; padding: 15px; border-radius: 8px; border: 1px solid var(--border-color); font-family: 'JetBrains Mono', monospace; font-size: 0.85rem; line-height: 1.8; color: var(--text-main);">
|
||||
<!-- Dati iniettati via JS -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/socket.io.min.js"></script>
|
||||
|
||||
<script>
|
||||
@@ -423,7 +465,7 @@
|
||||
ttProfA: "Switch to Profile A", ttProfB: "Switch to Profile B", ttTgOn: "Enable Telegram notifications", ttTgOff: "Disable Telegram notifications", ttSvc: "Manage system daemons", ttFile: "Edit .ini configuration files", ttHat: "Send physical reset to modem", ttBoot: "Reboot node operating system",
|
||||
ttSwitchTo: "Switch to profile: ", ttSvcStart: "Start service", ttSvcRestart: "Restart service", ttSvcEdit: "Edit configuration", ttSvcStop: "Stop service", ttLang: "Change language",
|
||||
statTopTG: "🎯 TOP TALKGROUPS", statTopCall: "🗣️ TOP CALLSIGNS", statLoading: "Loading...", statAvgDur: "⏱️ AVERAGE DURATION", statTodayTx: "📡 TRANSITS TODAY", statNoData: "No data",
|
||||
statTitle: "DAILY STATISTICS", statAllNodes: "ALL NODES"
|
||||
statTitle: "DAILY STATISTICS", statAllNodes: "ALL NODES", modVersions: "Software & Firmware"
|
||||
},
|
||||
it: {
|
||||
lastTransits: "Ultimi ascolti", loginTitle: "🔒 Login di Sistema",
|
||||
@@ -452,7 +494,7 @@
|
||||
ttProfA: "Passa al Profilo A", ttProfB: "Passa al Profilo B", ttTgOn: "Abilita notifiche Telegram", ttTgOff: "Disabilita notifiche Telegram", ttSvc: "Gestisci demoni di sistema", ttFile: "Modifica file .ini da remoto", ttHat: "Reset fisico scheda modem", ttBoot: "Riavvia sistema operativo",
|
||||
ttSwitchTo: "Passa al profilo: ", ttSvcStart: "Avvia servizio", ttSvcRestart: "Riavvia servizio", ttSvcEdit: "Modifica configurazione", ttSvcStop: "Ferma servizio", ttLang: "Cambia lingua",
|
||||
statTopTG: "🎯 TOP TALKGROUPS", statTopCall: "🗣️ TOP CALLSIGNS", statLoading: "Caricamento...", statAvgDur: "⏱️ DURATA MEDIA", statTodayTx: "📡 TRANSITI OGGI", statNoData: "Nessun dato",
|
||||
statTitle: "STATISTICHE GIORNALIERE", statAllNodes: "TUTTA LA RETE"
|
||||
statTitle: "STATISTICHE GIORNALIERE", statAllNodes: "TUTTA LA RETE", modVersions: "Software & Firmware"
|
||||
}
|
||||
};
|
||||
let currentLang = localStorage.getItem('lang') || 'en';
|
||||
@@ -475,13 +517,29 @@
|
||||
}
|
||||
|
||||
// --- HELPER DI SICUREZZA ---
|
||||
// esc(): escape HTML per tutto ciò che arriva da MQTT / database / utenti prima di finire in innerHTML
|
||||
function esc(s) { return String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
|
||||
// q(): letterale JS sicuro da usare dentro onclick="...": onclick="fn(${q(valore)})"
|
||||
function q(s) { return esc(JSON.stringify(String(s ?? ''))); }
|
||||
const HANG_TIME_MS = 180000; // tempo massimo in cui la card resta "accesa" dopo l'ultimo TX
|
||||
const HANG_TIME_MS = 180000;
|
||||
|
||||
// --- DIAGNOSTICA: "ultimo messaggio ricevuto" per nodo (MMDVM / gateway / agent) ---
|
||||
// --- GESTIONE SCHEDE (TABS) ---
|
||||
function switchView(viewName) {
|
||||
document.getElementById('view-home').style.display = 'none';
|
||||
document.getElementById('view-nodes').style.display = 'none';
|
||||
document.getElementById('tab-home').classList.remove('active');
|
||||
document.getElementById('tab-nodes').classList.remove('active');
|
||||
|
||||
document.getElementById(`view-${viewName}`).style.display = 'block';
|
||||
document.getElementById(`tab-${viewName}`).classList.add('active');
|
||||
|
||||
localStorage.setItem('fleetDefaultView', viewName);
|
||||
}
|
||||
|
||||
window.addEventListener('DOMContentLoaded', () => {
|
||||
const savedView = localStorage.getItem('fleetDefaultView') || 'home';
|
||||
switchView(savedView);
|
||||
});
|
||||
|
||||
// --- DIAGNOSTICA ---
|
||||
function fmtAge(sec) {
|
||||
sec = Math.max(0, Math.round(sec));
|
||||
if (sec < 60) return sec + 's';
|
||||
@@ -502,8 +560,6 @@
|
||||
const upSec = data.uptime || 0;
|
||||
let html = '';
|
||||
|
||||
// MMDVM: pubblica eventi (TX, cambio modo), quindi su un nodo tranquillo l'età può crescere senza problemi.
|
||||
// Si segnala solo il caso "mai ricevuto nulla" con nodo online e server attivo da un po'.
|
||||
const warnM = ages.mmdvm === undefined && isOnline && upSec > 600;
|
||||
const tipM = it ? `Ultimo evento dal topic mmdvm/${c.id}/json (TX, cambio modo...). Su un nodo tranquillo può passare molto tempo.`
|
||||
: `Last event from topic mmdvm/${c.id}/json (TX, mode change...). It can be a long time on a quiet node.`;
|
||||
@@ -511,13 +567,10 @@
|
||||
: `No MMDVM event received since the server started (${fmtAge(upSec)}): check that MMDVMHost is connected to the broker.`;
|
||||
html += seenItem('MMDVM', ages.mmdvm, warnM ? tipMW : tipM, warnM);
|
||||
|
||||
// Gateway: solo se il nodo ne ha mai pubblicati
|
||||
if (ages.gateway !== undefined) {
|
||||
html += seenItem('GW', ages.gateway, it ? 'Ultimo evento dai gateway (DMR/NXDN/YSF/P25/D-Star)' : 'Last event from the gateways (DMR/NXDN/YSF/P25/D-Star)', false);
|
||||
}
|
||||
|
||||
// Agent: heartbeat periodico, se tace a lungo con nodo "online" qualcosa non va
|
||||
// Soglia in base all'intervallo di telemetria dichiarato dall'agente (default 60 s): 3 intervalli, minimo 180 s
|
||||
const hObj = (data.health && data.health[c.id.toLowerCase()]) || {};
|
||||
const iv = Number(hObj.interval) > 0 ? Number(hObj.interval) : 60;
|
||||
const warnA = isOnline && (ages.health === undefined ? upSec > Math.max(300, iv * 5) : ages.health > Math.max(180, iv * 3));
|
||||
@@ -532,10 +585,11 @@
|
||||
|
||||
// --- GLOBAL VARIABLES ---
|
||||
let clients = [];
|
||||
let me = { logged_in: false, user: '', role: '', allowed_nodes: '' }; // stato reale della sessione (da /api/me)
|
||||
let me = { logged_in: false, user: '', role: '', allowed_nodes: '' };
|
||||
let isAuthenticated = false;
|
||||
let usersCache = {};
|
||||
let globalHealthData = {};
|
||||
let globalVersionsData = {}; // NUOVA VARIABILE VERSIONI
|
||||
let editingUserId = null;
|
||||
let currentResetHatId = null;
|
||||
let confirmActionCallback = null;
|
||||
@@ -596,8 +650,7 @@
|
||||
}
|
||||
|
||||
function confirmReboot(id) { sendCommand(id, 'REBOOT', `🔄 ${t('titleBoot')}`, `${t('confBoot')}<b>${id.toUpperCase()}</b>?`, "var(--danger)"); }
|
||||
function confirmUpdateAgent(id) { sendCommand(id, 'UPDATE_AGENT', `⬇️ UPDATE OTA`, `Confermi l'aggiornamento dello script tramite git pull sul nodo <b>${id.toUpperCase()}</b>?`, "#2563eb");
|
||||
}
|
||||
function confirmUpdateAgent(id) { sendCommand(id, 'UPDATE_AGENT', `⬇️ UPDATE OTA`, `Confermi l'aggiornamento dello script tramite git pull sul nodo <b>${id.toUpperCase()}</b>?`, "#2563eb"); }
|
||||
|
||||
function confirmHatReset(id) {
|
||||
currentResetHatId = id;
|
||||
@@ -648,7 +701,6 @@
|
||||
|
||||
const response = await fetch('/api/clients');
|
||||
clients = await response.json();
|
||||
// Gli id nodo finiscono in id HTML e onclick: accettiamo solo caratteri sicuri
|
||||
clients = clients.filter(c => /^[A-Za-z0-9_\-]+$/.test(String(c.id)));
|
||||
|
||||
const statSelect = document.getElementById('stat-node-filter');
|
||||
@@ -730,6 +782,7 @@
|
||||
` : ''}
|
||||
${showReboot ? `
|
||||
<div style="width: 100%; display: flex; gap: 8px;">
|
||||
<button class="btn-cmd" style="background: var(--primary); padding: 8px 4px;" title="Mostra Versioni Software" onclick="openVersionsModal('${c.id}')">ℹ️ INFO</button>
|
||||
<button id="btn-svc-${c.id}" class="btn-cmd" style="background: #334155; padding: 8px 4px;" title="${t('ttSvc')}" onclick="openServicesModal('${c.id}')">${t('btnSvc')}</button>
|
||||
<button class="btn-cmd" style="background: #8e44ad; padding: 8px 4px;" title="${t('ttFile')}" onclick="openConfigsModal('${c.id}')">${t('btnFile')}</button>
|
||||
<button class="btn-cmd" style="background: #ea580c; padding: 8px 4px;" title="${t('ttHat')}" onclick="confirmHatReset('${c.id}')">${t('btnHat')}</button>
|
||||
@@ -765,21 +818,23 @@
|
||||
async function refreshStates() {
|
||||
try {
|
||||
const res = await fetch('/api/states'); const data = await res.json();
|
||||
|
||||
// AGGIORNAMENTO DATI VERSIONI GLOBALI
|
||||
globalVersionsData = data.versions || {};
|
||||
|
||||
clients.forEach(c => {
|
||||
const statusDiv = document.getElementById(`status-${c.id}`); const cardDiv = document.getElementById(`card-${c.id}`);
|
||||
if (!statusDiv || !cardDiv) return;
|
||||
|
||||
// 1. PRIMA CALCOLIAMO SE È ONLINE
|
||||
let stateValue = data.states[c.id.toLowerCase()] || data.states[c.id] || "OFFLINE";
|
||||
stateValue = String(stateValue).trim().toUpperCase(); statusDiv.innerText = stateValue;
|
||||
const isOnline = !stateValue.includes("OFF") && stateValue !== "";
|
||||
renderSeen(c, data, isOnline);
|
||||
|
||||
// 2. POI AGGIORNIAMO NOME E ID DINAMICI
|
||||
let genObj = data.general && data.general[c.id.toLowerCase()];
|
||||
const nameSpan = cardDiv.querySelector('.client-name');
|
||||
const idBadge = cardDiv.querySelector('.badge-id');
|
||||
const typeBadge = document.getElementById(`type-badge-${c.id}`); // <--- Peschiamo il nostro nuovo badge
|
||||
const typeBadge = document.getElementById(`type-badge-${c.id}`);
|
||||
|
||||
if (genObj && isOnline) {
|
||||
nameSpan.innerText = genObj.callsign;
|
||||
@@ -788,7 +843,6 @@
|
||||
idBadge.style.color = "#ffffff";
|
||||
idBadge.style.borderColor = "var(--primary)";
|
||||
|
||||
// --- LOGICA BADGE HOTSPOT/REPEATER ---
|
||||
if (typeBadge && genObj.duplex !== undefined) {
|
||||
typeBadge.style.display = 'inline-block';
|
||||
if (genObj.duplex === "1") {
|
||||
@@ -806,10 +860,9 @@
|
||||
idBadge.style.color = "var(--text-muted)";
|
||||
idBadge.style.borderColor = "var(--border-color)";
|
||||
|
||||
if (typeBadge) typeBadge.style.display = 'none'; // Nascondilo se il nodo va offline
|
||||
if (typeBadge) typeBadge.style.display = 'none';
|
||||
}
|
||||
|
||||
// 3. TELEMETRIA E STATO (PULITO DAI DUPLICATI)
|
||||
let telemetryObj = data.telemetry[c.id.toLowerCase()] || data.telemetry[c.id] || { ts1: "...", ts2: "...", alt: "", idle: true };
|
||||
if (typeof telemetryObj === 'string') telemetryObj = { ts1: telemetryObj, ts2: "...", alt: "", idle: true };
|
||||
|
||||
@@ -840,14 +893,10 @@
|
||||
activeModeColor = "var(--primary)";
|
||||
|
||||
if (ts1Div && ts2Div) {
|
||||
// --- LOGICA DUPLEX / SIMPLEX ---
|
||||
let isSimplex = (genObj && genObj.duplex === "0");
|
||||
|
||||
// Nascondiamo il div del TS1 se il nodo è Simplex
|
||||
ts1Div.style.display = isSimplex ? 'none' : 'block';
|
||||
|
||||
[ts1Div, ts2Div].forEach((div, idx) => {
|
||||
// Se è simplex, saltiamo del tutto l'aggiornamento grafico del TS1
|
||||
if (isSimplex && idx === 0) return;
|
||||
|
||||
const val = String((idx === 0 ? telemetryObj.ts1 : telemetryObj.ts2) ?? ''); const netName = idx === 0 ? netObj.ts1 : netObj.ts2;
|
||||
@@ -937,15 +986,12 @@
|
||||
if (isOnline) {
|
||||
cardDiv.classList.add('online'); statusDiv.classList.remove('status-offline'); cardDiv.style.opacity = "1"; cardDiv.style.filter = "none";
|
||||
|
||||
// --- INIZIO LOGICA SMART HANG-TIME ---
|
||||
if (isTx) cardDiv.dataset.lastTx = Date.now(); // Memorizza quando è avvenuto l'ultimo TX
|
||||
if (isTx) cardDiv.dataset.lastTx = Date.now();
|
||||
let timeSinceTx = Date.now() - (parseInt(cardDiv.dataset.lastTx) || 0);
|
||||
|
||||
// Accendi se in TX, OPPURE se in Hang Time (ma spegni a forza dopo HANG_TIME_MS di inattività)
|
||||
let showActiveColor = isTx || (!isIdle && timeSinceTx < HANG_TIME_MS);
|
||||
|
||||
cardDiv.style.setProperty('border-top-color', showActiveColor ? activeModeColor : "var(--border-color)", 'important');
|
||||
// --- FINE LOGICA ---
|
||||
if(isTx) {
|
||||
let shadowRGB = '59, 130, 246';
|
||||
if (activeModeColor === '#10b981') shadowRGB = '16, 185, 129';
|
||||
@@ -971,7 +1017,7 @@
|
||||
const time = row[0] ? row[0].split(' ')[1] : "--:--";
|
||||
const clientId = row[1]; const protocol = row[2] || "DMR"; let source = row[3] || "---"; const target = row[4] || "---";
|
||||
const rawSlot = row[5]; const source_ext = row[8];
|
||||
const rawRssi = row[9]; // Estrai il nuovo valore
|
||||
const rawRssi = row[9];
|
||||
|
||||
let sourceHtml = esc(source);
|
||||
if (source_ext && source_ext.trim() !== "") { sourceHtml += ` <span style="font-size:0.8em; color:#94a3b8; font-family:'JetBrains Mono', monospace;">/${esc(source_ext)}</span>`; }
|
||||
@@ -979,31 +1025,57 @@
|
||||
const slotDisplay = protocol === "DMR" ? `TS${rawSlot}` : "--";
|
||||
let protoColor = "#3b82f6"; if (protocol === "NXDN") protoColor = "#10b981"; else if (protocol === "YSF") protoColor = "#8b5cf6"; else if (protocol === "D-STAR") protoColor = "#06b6d4"; else if (protocol === "P25") protoColor = "#f59e0b";
|
||||
|
||||
// Formatta l'RSSI con S-Meter grafico (nascondilo se è 0)
|
||||
// Formatta l'RSSI con S-Meter grafico a segmenti
|
||||
let rssiDisplay = '---';
|
||||
if (rawRssi && rawRssi !== 0) {
|
||||
// Calcola la percentuale su un range utile di 80 dB (da -130 a -50 dBm)
|
||||
const pct = Math.max(0, Math.min(100, ((rawRssi + 130) / 80) * 100));
|
||||
// Calcolo livello S-Meter (Standard VHF/UHF: S9 = -93 dBm, 6dB per punto S)
|
||||
let sLabel = "S0";
|
||||
if (rawRssi >= -93) {
|
||||
let over = Math.round((rawRssi + 93) / 10) * 10;
|
||||
sLabel = over > 0 ? `S9<sup style="color: var(--danger); font-weight: 800;">+${over}</sup>` : "S9";
|
||||
} else {
|
||||
let sUnits = Math.floor((rawRssi + 141) / 6) + 1;
|
||||
sLabel = `S${Math.max(1, Math.min(9, sUnits))}`;
|
||||
}
|
||||
|
||||
// Assegna il colore in stile S-Meter amatoriale
|
||||
let barColor = "var(--success)"; // Verde (fino a S9 / -93 dBm)
|
||||
if (rawRssi > -93) barColor = "#f59e0b"; // Giallo (S9+)
|
||||
if (rawRssi > -73) barColor = "var(--danger)"; // Rosso (S9+20 o superiore)
|
||||
// Calcolo segmenti accesi (9 segmenti totali)
|
||||
let activeSegs = 1;
|
||||
if (rawRssi >= -53) activeSegs = 9;
|
||||
else if (rawRssi >= -63) activeSegs = 8;
|
||||
else if (rawRssi >= -73) activeSegs = 7;
|
||||
else if (rawRssi >= -83) activeSegs = 6;
|
||||
else if (rawRssi >= -93) activeSegs = 5; // S9
|
||||
else if (rawRssi >= -105) activeSegs = 4;
|
||||
else if (rawRssi >= -117) activeSegs = 3;
|
||||
else if (rawRssi >= -129) activeSegs = 2;
|
||||
|
||||
rssiDisplay = `
|
||||
<div style="display: flex; align-items: center; gap: 8px;" title="${esc(rawRssi)} dBm">
|
||||
<div style="width: 50px; height: 6px; background: rgba(255,255,255,0.1); border-radius: 3px; overflow: hidden; box-shadow: inset 0 1px 2px rgba(0,0,0,0.5);">
|
||||
<div style="width: ${pct}%; height: 100%; background: ${barColor}; transition: width 0.3s ease;"></div>
|
||||
</div>
|
||||
<span style="font-size: 0.85em; color: var(--text-muted); min-width: 3ch;">${esc(rawRssi)}</span>
|
||||
</div>`;
|
||||
// Generazione barre HTML
|
||||
let barsHtml = '';
|
||||
const heights = [4, 5, 6, 7, 8, 10, 12, 14, 14];
|
||||
for (let i = 0; i < 9; i++) {
|
||||
let color = "rgba(255,255,255,0.1)"; // Spento
|
||||
if (i < activeSegs) {
|
||||
if (i < 5) color = "var(--success)"; // Verde
|
||||
else if (i < 7) color = "#f59e0b"; // Giallo
|
||||
else color = "var(--danger)"; // Rosso
|
||||
}
|
||||
barsHtml += `<div style="width: 4px; height: ${heights[i]}px; background: ${color}; border-radius: 1px;"></div>`;
|
||||
}
|
||||
|
||||
rssiDisplay = `
|
||||
<div style="display: flex; align-items: center; gap: 10px;" title="${esc(rawRssi)} dBm">
|
||||
<div style="min-width: 40px; text-align: right; font-weight: bold; font-family: 'Inter', sans-serif;">${sLabel}</div>
|
||||
<div style="display: flex; align-items: flex-end; gap: 2px; height: 14px;">
|
||||
${barsHtml}
|
||||
</div>
|
||||
<span style="font-size: 0.85em; color: var(--text-muted); min-width: 7ch; text-align: right;">${esc(rawRssi)} dBm</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
if (source.includes("🌐")) {
|
||||
if (!networkLogs[clientId]) networkLogs[clientId] = "";
|
||||
networkLogs[clientId] += `<div style="border-bottom:1px solid rgba(255,255,255,0.1); padding:4px 0;"><span style="color:#64748b;">[${esc(time)}]</span> <span style="color:${protoColor}; font-weight:bold;">[${esc(protocol)}]</span> <span style="color:#cbd5e1;">${esc(source.replace("🌐", "").trim())}</span></div>`;
|
||||
} else {
|
||||
// Aggiunto il TD per l'RSSI alla fine
|
||||
tableHTML += `<tr><td>${esc(time)}</td><td><b style="color:var(--text-main);">${esc(String(clientId).toUpperCase())}</b></td><td><span style="background:${protoColor}; color:white; padding:3px 8px; border-radius:8px; font-size:0.7rem; font-weight:800;">${esc(protocol)}</span></td><td style="font-family:'JetBrains Mono', monospace; font-weight:bold; text-align:center;">${esc(slotDisplay)}</td><td style="color:var(--accent); font-weight:800;">${sourceHtml}</td><td style="font-family:'JetBrains Mono', monospace;">${esc(target.trim())}</td><td>${esc(row[6])}s</td><td>${esc(row[7])}%</td><td style="font-family:'JetBrains Mono', monospace;">${rssiDisplay}</td></tr>`;
|
||||
}
|
||||
});
|
||||
@@ -1070,7 +1142,6 @@
|
||||
// --- SETTINGS ---
|
||||
function triggerGlobalEmergency() {
|
||||
let uniqueProfiles = {};
|
||||
// Raccoglie tutti i profili unici trovati nei nodi online
|
||||
for (const id in globalHealthData) {
|
||||
if (globalHealthData[id] && globalHealthData[id].profiles) {
|
||||
for (const [k, v] of Object.entries(globalHealthData[id].profiles)) {
|
||||
@@ -1126,10 +1197,19 @@
|
||||
}
|
||||
|
||||
// --- SERVICES & CONFIGS ---
|
||||
function fileLabel(stem, names) {
|
||||
const key = String(stem).toLowerCase();
|
||||
const full = (names || []).find(n => String(n).replace(/\.[^.]*$/, '').toLowerCase() === key);
|
||||
if (full) {
|
||||
const m = String(full).match(/^(.*?)(\.[^.]*)?$/);
|
||||
return String(m[1]).toUpperCase() + (m[2] || '');
|
||||
}
|
||||
return String(stem).toUpperCase() + '.ini';
|
||||
}
|
||||
function openConfigsModal(clientId) {
|
||||
const data = globalHealthData[clientId.toLowerCase()]; const listDiv = document.getElementById('configs-list'); let listaFile = data ? (data.config_files || data.files || []) : [];
|
||||
const data = globalHealthData[clientId.toLowerCase()]; const listDiv = document.getElementById('configs-list'); let listaFile = data ? (data.config_files || data.files || []) : []; const fileNames = (data && data.file_names) || [];
|
||||
if (listaFile.length === 0) listDiv.innerHTML = `<div style="text-align:center; padding:20px;"><p style="color:var(--text-muted); margin-bottom:15px;">${t('waitData')}</p><button onclick="sendGlobalUpdate(); closeConfigsModal();" class="btn-cmd" style="background:var(--accent);">${t('forceUpdate')}</button></div>`;
|
||||
else listDiv.innerHTML = listaFile.map(f => `<div style="display:flex; justify-content:space-between; align-items:center; padding:12px; background:rgba(128,128,128,0.1); border-radius:12px; border:1px solid var(--border-color); margin-bottom:8px;"><span style="font-family:'JetBrains Mono',monospace; font-weight:bold;">${esc(String(f).toUpperCase())}.ini</span><button onclick="closeConfigsModal(); openEditorModal(${q(clientId)}, ${q(f)})" class="btn-cmd" style="background:#8e44ad; max-width:120px;">${t('btnEdit')}</button></div>`).join('');
|
||||
else listDiv.innerHTML = listaFile.map(f => `<div style="display:flex; justify-content:space-between; align-items:center; padding:12px; background:rgba(128,128,128,0.1); border-radius:12px; border:1px solid var(--border-color); margin-bottom:8px;"><span style="font-family:'JetBrains Mono',monospace; font-weight:bold;">${esc(fileLabel(f, fileNames))}</span><button onclick="closeConfigsModal(); openEditorModal(${q(clientId)}, ${q(f)})" class="btn-cmd" style="background:#8e44ad; max-width:120px;">${t('btnEdit')}</button></div>`).join('');
|
||||
document.getElementById('configs-modal').style.display = 'flex';
|
||||
}
|
||||
function closeConfigsModal() { document.getElementById('configs-modal').style.display = 'none'; }
|
||||
@@ -1185,10 +1265,32 @@
|
||||
});
|
||||
}
|
||||
|
||||
// --- NUOVE FUNZIONI PER POP-UP VERSIONI ---
|
||||
function openVersionsModal(clientId) {
|
||||
const versions = globalVersionsData[clientId.toLowerCase()];
|
||||
const listDiv = document.getElementById('versions-list');
|
||||
|
||||
if (!versions || Object.keys(versions).length === 0) {
|
||||
listDiv.innerHTML = "<span style='color: var(--text-muted);'>Nessun dato ancora ricevuto. Usa il tasto 🔄 RESTART sui servizi del nodo per forzare l'invio del log di avvio.</span>";
|
||||
} else {
|
||||
let html = "";
|
||||
for (const [software, version] of Object.entries(versions)) {
|
||||
html += `<div><strong style="color: var(--primary); display: inline-block; width: 140px;">${esc(software)}:</strong> <span style="color: var(--success); font-weight: bold;">${esc(version)}</span></div>`;
|
||||
}
|
||||
listDiv.innerHTML = html;
|
||||
}
|
||||
|
||||
document.getElementById('versions-modal').style.display = 'flex';
|
||||
}
|
||||
|
||||
function closeVersionsModal() {
|
||||
document.getElementById('versions-modal').style.display = 'none';
|
||||
}
|
||||
|
||||
// --- PUSH NOTIFICATIONS ---
|
||||
async function subscribeToPush() {
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) { customAlert("Error", "Push notifications are not supported by this browser.", true); return; }
|
||||
if (!me.logged_in) { openLoginModal(); return; } // le notifiche si attivano solo da loggati
|
||||
if (!me.logged_in) { openLoginModal(); return; }
|
||||
const permission = await Notification.requestPermission();
|
||||
if (permission !== 'granted') { customAlert("Error", "Push notifications permission denied.", true); return; }
|
||||
try {
|
||||
@@ -1209,7 +1311,6 @@
|
||||
checkPushStatus();
|
||||
|
||||
// --- AGGIORNAMENTI PERIODICI ---
|
||||
// Fallback se il WebSocket non è disponibile + spegne l'hang time scaduto anche senza nuovi eventi
|
||||
setInterval(refreshStates, 15000);
|
||||
setInterval(() => { refreshLogs(); refreshStats(); }, 60000);
|
||||
|
||||
@@ -1225,8 +1326,8 @@
|
||||
if (badge) { if (data.connected) { badge.innerText = "MQTT: ONLINE"; badge.className = "mqtt-badge mqtt-online"; } else { badge.innerText = "MQTT: OFFLINE"; badge.className = "mqtt-badge mqtt-offline"; } }
|
||||
});
|
||||
socket.on('connect', () => { refreshStates(); refreshLogs(); refreshStats(); });
|
||||
socket.on('dati_aggiornati', refreshStatesSoon); // stato nodi / telemetria
|
||||
socket.on('log_aggiornato', refreshLogsSoon); // nuovi ascolti -> lastheard + statistiche
|
||||
socket.on('dati_aggiornati', refreshStatesSoon);
|
||||
socket.on('log_aggiornato', refreshLogsSoon);
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
|
||||
Reference in New Issue
Block a user