Compare commits

...
6 Commits
Author SHA1 Message Date
iv3jdv 35f1598393 feat(ui): feedback visivo TX sui mini-badge della home
Implementato il riconoscimento dello stato di trasmissione nei mini-badge della schermata principale. I badge ora si illuminano mostrando '🎙️ TX' con bordo e ombreggiatura dinamica abbinata al colore del modo digitale attivo (DMR, YSF, NXDN, ecc.), prioritizzando la visibilità del transito.
2026-10-25 15:52:10 +01:00
iv3jdv 9a4dc1eea7 feat(mqtt): supporto coordinate e info da DMRGateway
Aggiunto 'dmrgateway' ai topic validi per il recupero dei dati di geolocalizzazione (Lat, Lon, Loc). Implementato il merge incrementale dei parametri per permettere a MMDVMHost e DMRGateway di popolare le info del nodo senza sovrascriversi a vicenda, in previsione della deprecazione della sezione [Info] su MMDVM.
2026-10-25 15:22:51 +01:00
iv3jdv be0cbbb64b fix scroll home 2026-10-25 12:42:55 +01:00
iv3jdv 6d11c355df fix(watchdog): ridotta finestra temporale alert BER a 5 minuti
Aggiornata la query di analisi diagnostica nel watchdog per calcolare la media del BER sugli ultimi 5 minuti (invece di 2 ore). Ridotto il numero minimo di transiti necessari per l'innesco, garantendo un feedback immediato nella dashboard e la scomparsa rapida dell'allarme in assenza di traffico degradato.
2026-10-25 12:28:20 +01:00
iv3jdv efca23c64f feat(logs): limite configurabile e selettore righe Last Heard con i18n
Aggiunto il supporto per definire il numero di righe del Last Heard tramite configurazione (config.json) e query string (?limit=). Inserito nel frontend un selettore a tendina con persistenza in localStorage ed etichetta bilingue (IT/EN).
2026-10-25 11:54:20 +01:00
iv3jdv 69308c4580 fix(mqtt): parsing intelligente stati gateway YSF e NXDN" -m "Risolto il problema di visualizzazione dei badge YSF e NXDN nella dashboard. Aggiunto il parsing testuale dei messaggi MQTT per intercettare correttamente le connessioni ('Linked to', 'Switched to reflector') e le disconnessioni ('stopping'), ignorando i messaggi di heartbeat ed evitando che la fase di avvio cancelli lo stato del reflector appena agganciato 2026-10-25 11:14:09 +01:00
7 changed files with 158 additions and 51 deletions
+2 -1
View File
@@ -39,5 +39,6 @@
"nxdn": "https://radioid.net/static/nxdn.csv"
},
"log_max_mb": 50,
"log_backup_count": 10
"log_backup_count": 10,
"last_heard_limit": 60
}
+11 -1
View File
@@ -47,10 +47,20 @@ def get_clients():
@api_bp.route('/api/logs')
def get_logs():
# 1. Recupera il valore da config.json (default: 60)
cfg_limit = config.get("last_heard_limit", 60)
# 2. Se il client passa ?limit=, usa quello (validato tra 10 e 300 righe)
try:
limit = int(request.args.get('limit', cfg_limit))
limit = max(10, min(limit, 300))
except (ValueError, TypeError):
limit = cfg_limit
conn = sqlite3.connect(DB_PATH, timeout=10)
c = conn.cursor()
c.execute("""SELECT timestamp, client_id, protocol, source_id, target, slot, duration, ber, source_ext, rssi, source_conn, ysf_mode
FROM radio_logs ORDER BY id DESC LIMIT 60""")
FROM radio_logs ORDER BY id DESC LIMIT ?""", (limit,))
logs = c.fetchall()
conn.close()
return jsonify(logs)
+71 -34
View File
@@ -182,17 +182,11 @@ def on_message(client, userdata, msg):
logger.error(f"Errore parsing telemetria agent: {e}")
# --- 5. INFO FREQUENZE E GEOLOCALIZZAZIONE ---
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost') and parts[3].lower() == 'info':
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost', 'dmrgateway') and parts[3].lower() == 'info':
try:
cid = parts[1].lower()
data = json.loads(payload)
tx = data.get("TXFrequency", "0")
rx = data.get("RXFrequency", "0")
lat = data.get("Latitude", "0.0")
lon = data.get("Longitude", "0.0")
loc = data.get("Location", "Sconosciuta")
def format_freq(f):
if str(f).isdigit() and int(f) > 0:
hz = int(f)
@@ -202,17 +196,26 @@ def on_message(client, userdata, msg):
dec = dec[:-1]
return f"{mhz}.{dec} MHz"
return str(f)
# Inizializza il dizionario se il nodo è nuovo
if cid not in state.node_info:
state.node_info[cid] = {"tx": "0", "rx": "0", "lat": "0.0", "lon": "0.0", "loc": "Sconosciuta"}
# Aggiorna solo i campi effettivamente presenti nel payload per fondere i dati di MMDVM e DMRGateway
if "TXFrequency" in data:
state.node_info[cid]["tx"] = format_freq(data["TXFrequency"])
if "RXFrequency" in data:
state.node_info[cid]["rx"] = format_freq(data["RXFrequency"])
if "Latitude" in data:
state.node_info[cid]["lat"] = data["Latitude"]
if "Longitude" in data:
state.node_info[cid]["lon"] = data["Longitude"]
if "Location" in data:
state.node_info[cid]["loc"] = data["Location"]
state.node_info[cid] = {
"tx": format_freq(tx),
"rx": format_freq(rx),
"lat": lat,
"lon": lon,
"loc": loc
}
state.notify_update()
except Exception as e:
logger.error(f"Errore parsing MMDVMHost info per {cid}: {e}")
logger.error(f"Errore parsing info (MMDVM/DMRGateway) per {cid}: {e}")
# --- 6. INFO GENERALI (CALLSIGN & RADIO ID) ---
elif len(parts) >= 4 and p0 == 'data' and p2 in ('mmdvm', 'mmdvmhost') and parts[3].lower() == 'general':
@@ -240,33 +243,67 @@ def on_message(client, userdata, msg):
if cid not in state.gateway_states:
state.gateway_states[cid] = {}
m = "" # Variabile per il log di sistema
if 'status' in data:
state.gateway_states[cid][proto] = {"action": "status", "dest": data['status'].get('message', 'IDLE')}
state.notify_update()
elif 'link' in data:
# 1. Parsing strutturato (usato per il messaggio "Link IT-YSF-FVG")
if 'link' in data:
l = data['link']
g_dest = str(l.get('reflector') or l.get('talkgroup') or '---').strip()
g_action = l.get('action', '')
state.gateway_states[cid][proto] = {"action": g_action, "dest": g_dest}
state.notify_update()
m = ""
if 'status' in data:
m = data['status'].get('message', '')
elif 'link' in data:
l = data['link']
dest = str(l.get('reflector') or l.get('talkgroup') or '---').strip()
action = l.get('action')
if action == 'linking':
state.last_seen_reflector[f"{cid}_{proto}"] = dest
elif action == 'unlinking':
if g_action == 'linking':
state.last_seen_reflector[f"{cid}_{proto}"] = g_dest
elif g_action == 'unlinking':
state.last_seen_reflector[f"{cid}_{proto}"] = "---"
m = f"{'Link' if action=='linking' else 'Unlinked'} {dest}"
m = f"{'Link' if g_action=='linking' else 'Unlinked'} {g_dest}"
# 2. Parsing testuale (usato per gli status testuali)
elif 'status' in data:
raw_msg = str(data['status'].get('message', 'IDLE'))
msg_lower = raw_msg.lower()
m = raw_msg
# A. NXDN: Connessione tramite RF
if "switched to reflector" in msg_lower:
match = re.search(r'switched to reflector (\w+)', msg_lower)
if match:
state.gateway_states[cid][proto] = {"action": "linked", "dest": match.group(1).upper()}
state.notify_update()
# B. YSF/NXDN: Connessione standard
elif "linked to" in msg_lower:
idx = msg_lower.find("linked to")
dest = raw_msg[idx + 9:].strip()
state.gateway_states[cid][proto] = {"action": "linked", "dest": dest}
state.notify_update()
# C. Connessione in corso
elif "linking to" in msg_lower:
idx = msg_lower.find("linking to")
dest = raw_msg[idx + 10:].strip()
state.gateway_states[cid][proto] = {"action": "linking", "dest": dest}
state.notify_update()
# D. Disconnessione o arresto del demone (Azzera la memoria)
elif "unlinked" in msg_lower or "disconnected" in msg_lower or "not linked" in msg_lower or "failed" in msg_lower or "stopping" in msg_lower:
state.gateway_states[cid][proto] = {"action": "unlinked", "dest": ""}
state.notify_update()
# E. Avvio del demone
elif "starting" in msg_lower or "opening" in msg_lower or "idle" in msg_lower:
# Azzera il badge SOLO se non è appena stato registrato un "Link" fulmineo
current_act = state.gateway_states.get(cid, {}).get(proto, {}).get("action")
if current_act not in ["linked", "linking"]:
state.gateway_states[cid][proto] = {"action": "idle", "dest": ""}
state.notify_update()
# Salvataggio nel DB per la console log
if m and "running" not in m.lower():
save_to_sqlite(cid, {'src_id': f"🌐 {m}", 'dst_id': 'NET'}, protocol=proto)
if m:
save_to_sqlite(cid, {'src_id': "🌐 " + m, 'dst_id': 'NET'}, protocol=proto)
# --- 8. TRAFFICO VOCE MMDVM (DMR & MODI DIGITALI) ---
elif parts[0] == 'mmdvm':
data = json.loads(payload)
+2 -2
View File
@@ -51,7 +51,7 @@ def run_diagnostics():
cur.execute("""
SELECT LOWER(client_id), AVG(ber), COUNT(*)
FROM radio_logs
WHERE timestamp >= datetime('now', 'localtime', '-2 hours')
WHERE timestamp >= datetime('now', 'localtime', '-5 minutes')
AND source_id NOT LIKE '🌐%'
AND (source_conn IS NULL OR LOWER(source_conn) != 'network')
GROUP BY LOWER(client_id)
@@ -60,7 +60,7 @@ def run_diagnostics():
for cid, avg_ber, cnt in rows:
key_ber = f"{cid}_BER"
if cnt >= 5 and avg_ber is not None and avg_ber >= 5.0:
if cnt >= 2 and avg_ber is not None and avg_ber >= 5.0:
new_warnings.setdefault(cid, []).append(f"⚠️ Alto BER RF ({avg_ber:.1f}%)")
if not watchdog_notified.get(key_ber):
broadcast_push_notification(f"⚠️ ANOMALIA RF: {cid.upper()}", f"Rilevato BER medio del {avg_ber:.1f}% negli ultimi {cnt} passaggi RF.", cid=cid)
+56 -10
View File
@@ -28,6 +28,9 @@ function switchView(viewName) {
document.getElementById(`tab-${viewName}`).classList.add('active');
localStorage.setItem('fleetDefaultView', viewName);
// Riporta la pagina in cima con un'animazione fluida
window.scrollTo({ top: 0, behavior: 'smooth' });
if (viewName === 'nodes') { applyViewMode(); }
else if (viewName === 'map') {
setTimeout(() => {
@@ -206,6 +209,11 @@ async function initUI() {
statSelect.innerHTML = opts;
}
const limitSel = document.getElementById('log-limit-select');
if (limitSel) {
limitSel.value = localStorage.getItem('fleetLogLimit') || '60';
}
const grid = document.getElementById('client-grid');
const authContainer = document.getElementById('auth-container');
const role = me.role || '';
@@ -538,7 +546,7 @@ async function refreshStates() {
{ id: 'p25gateway', label: 'P25', color: '#f59e0b', tint: 'rgba(245, 158, 11, 0.15)', proto: 'P25' }
];
if (isOnline) {
if (isOnline) {
gwMap.forEach(gw => {
let isActiveProc = processes[gw.id] && processes[gw.id].toLowerCase() === 'online';
if (isActiveProc) {
@@ -554,7 +562,7 @@ if (isOnline) {
badgeColor = 'white';
badgeBorder = gw.color;
suffix = dest ? `: ${dest} [LINKING]` : ` [LINKING]`;
} else if (action === 'linked' || (dest !== '' && action !== 'unlinked' && action !== 'failed')) {
} else if (action === 'linked' || (dest !== '' && action !== 'unlinked' && action !== 'failed' && action !== 'status')) {
badgeBg = gw.color;
badgeColor = 'white';
badgeBorder = gw.color;
@@ -578,7 +586,7 @@ if (isOnline) {
if (gw.proto === 'DMR' && gwData['DMR_NETS'] && gwData['DMR_NETS'].length > 0) {
gwData['DMR_NETS'].forEach(netName => {
let netSuffix = (action === 'linking') ? ' [LINKING]' : (action === 'failed' ? ' [FAILED]' : (dest ? `: ${dest}` : ''));
let netSuffix = (action === 'linking') ? ' [LINKING]' : (action === 'failed' ? ' [FAILED]' : (dest && action !== 'status' ? `: ${dest}` : ''));
let netText = `DMR: ${esc(netName)}${esc(netSuffix)}`;
gwHtml += `<span class="${extraClass}" style="font-size: 0.65rem; font-family: 'JetBrains Mono', monospace; font-weight: 800; padding: 3px 6px; border-radius: 4px; border: 1px solid ${badgeBorder}; background: ${badgeBg}; color: ${badgeColor} !important; transition: all 0.3s ease;" title="Stato: ${action.toUpperCase()}">${netText}</span>`;
});
@@ -705,18 +713,49 @@ if (isOnline) {
}
if (isOnline) {
miniCard.style.borderColor = (warns.length > 0) ? "#f59e0b" : "var(--success)";
let timeSinceTx = Date.now() - (parseInt(cardDiv.dataset.lastTx) || 0);
let showActiveColor = isTx || (!isIdle && timeSinceTx < HANG_TIME_MS);
miniCard.style.opacity = "1";
miniCard.style.filter = "none";
miniStatus.innerText = (warns.length > 0) ? "⚠️ ALERT" : stateValue;
miniStatus.title = (warns.length > 0) ? warns.join(" | ") : stateValue;
miniStatus.style.color = (warns.length > 0) ? "#f59e0b" : "var(--success)";
miniStatus.style.background = (warns.length > 0) ? "rgba(245, 158, 11, 0.15)" : "rgba(16, 185, 129, 0.1)";
miniStatus.style.borderColor = (warns.length > 0) ? "rgba(245, 158, 11, 0.4)" : "rgba(16, 185, 129, 0.2)";
if (showActiveColor) {
let shadowRGB = '59, 130, 246';
if (activeModeColor === '#10b981') shadowRGB = '16, 185, 129';
else if (activeModeColor === '#8b5cf6') shadowRGB = '139, 92, 246';
else if (activeModeColor === '#06b6d4') shadowRGB = '6, 182, 212';
else if (activeModeColor === '#f59e0b') shadowRGB = '245, 158, 11';
miniCard.style.borderColor = activeModeColor;
miniCard.style.boxShadow = `0 0 15px rgba(${shadowRGB}, 0.5)`;
miniStatus.innerText = "🎙️ TX";
miniStatus.title = "Transmitting...";
miniStatus.style.color = "#ffffff";
miniStatus.style.background = activeModeColor;
miniStatus.style.borderColor = activeModeColor;
}
else if (warns.length > 0) {
miniCard.style.borderColor = "#f59e0b";
miniCard.style.boxShadow = "none";
miniStatus.innerText = "⚠️ ALERT";
miniStatus.title = warns.join(" | ");
miniStatus.style.color = "#f59e0b";
miniStatus.style.background = "rgba(245, 158, 11, 0.15)";
miniStatus.style.borderColor = "rgba(245, 158, 11, 0.4)";
} else {
miniCard.style.borderColor = "var(--success)";
miniCard.style.boxShadow = "none";
miniStatus.innerText = stateValue;
miniStatus.title = stateValue;
miniStatus.style.color = "var(--success)";
miniStatus.style.background = "rgba(16, 185, 129, 0.1)";
miniStatus.style.borderColor = "rgba(16, 185, 129, 0.2)";
}
} else {
miniCard.style.borderColor = "var(--border-color)";
miniCard.style.opacity = "0.6";
miniCard.style.filter = "grayscale(80%)";
miniCard.style.boxShadow = "none";
miniStatus.innerText = "OFFLINE";
miniStatus.title = "OFFLINE";
miniStatus.style.color = "var(--danger)";
@@ -734,9 +773,16 @@ if (isOnline) {
} catch (e) { console.error(e); }
}
function changeLogLimit(val) {
localStorage.setItem('fleetLogLimit', val);
refreshLogs();
}
async function refreshLogs() {
try {
const res = await fetch('/api/logs'); const logs = await res.json();
const savedLimit = localStorage.getItem('fleetLogLimit') || '';
const url = savedLimit ? `/api/logs?limit=${encodeURIComponent(savedLimit)}` : '/api/logs';
const res = await fetch(url); const logs = await res.json();
const tbody = document.getElementById('log-body'); let tableHTML = ""; let networkLogs = {};
logs.forEach(row => {
const time = row[0] ? row[0].split(' ')[1] : "--:--";
+2
View File
@@ -1,6 +1,7 @@
// --- SISTEMA TRADUZIONI (i18n) & HELPERS ---
const i18n = {
en: {
lblLogLimit: "Rows:",
lastTransits: "Lastheard", loginTitle: "🔒 System Login",
thTime: "Time", thRep: "Repeater", thMode: "Mode", thCall: "Callsign", thDur: "Duration",
thUser: "User", thRole: "Role", thNodes: "Nodes", thActs: "Actions",
@@ -31,6 +32,7 @@ const i18n = {
filtAll: "All Nodes", filtOnline: "Online", filtOffline: "Offline", filtAlerts: "⚠️ Alerts"
},
it: {
lblLogLimit: "Righe:",
lastTransits: "Ultimi ascolti", loginTitle: "🔒 Login di Sistema",
thTime: "Ora", thRep: "Ripetitore", thMode: "Modo", thCall: "Nominativo", thDur: "Durata",
thUser: "Utente", thRole: "Ruolo", thNodes: "Nodi", thActs: "Azioni",
+14 -3
View File
@@ -84,9 +84,20 @@
<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="lastTransits">Lastheard</span>
</h3>
<select id="stat-node-filter" onchange="refreshStats(); refreshLogs();" style="font-weight: bold; cursor: pointer;">
<option value="all">🌐 ALL NODES</option>
</select>
<div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
<div style="display: flex; align-items: center; gap: 6px;">
<label for="log-limit-select" data-i18n="lblLogLimit" style="font-size: 0.8rem; color: var(--text-muted); font-weight: 600;">Righe:</label>
<select id="log-limit-select" onchange="changeLogLimit(this.value)" style="font-weight: bold; cursor: pointer; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--border-color); background: rgba(0,0,0,0.2); color: var(--text-main);">
<option value="30">30</option>
<option value="60">60</option>
<option value="100">100</option>
<option value="200">200</option>
</select>
</div>
<select id="stat-node-filter" onchange="refreshStats(); refreshLogs();" style="font-weight: bold; cursor: pointer;">
<option value="all">🌐 ALL NODES</option>
</select>
</div>
</div>
<div class="table-container" style="margin-bottom: 0;">
<table>