diff --git a/core/state.py b/core/state.py index b70048d..26c1e6e 100644 --- a/core/state.py +++ b/core/state.py @@ -47,6 +47,7 @@ node_versions = {} gateway_states = {} active_warnings = {} active_calls = {} +operating_modes = {} # Caricamento iniziale cache telemetria if os.path.exists(CACHE_FILE): diff --git a/routes/api_routes.py b/routes/api_routes.py index eec417e..de09ab4 100644 --- a/routes/api_routes.py +++ b/routes/api_routes.py @@ -104,7 +104,8 @@ def get_states(): "uptime": int(time.time() - state.START_TIME), "versions": clean_versions, "gateway_states": enriched_gateway_states, - "warnings": state.active_warnings + "warnings": state.active_warnings, + "modes": getattr(state, "operating_modes", {}) }) @api_bp.route('/api/stats') @@ -346,6 +347,11 @@ def save_config_file(): if not mqtt_publish(f"devices/{cid}/config_set/{service}", json.dumps(new_config)): return err("Broker MQTT non raggiungibile", 503) audit(auth['username'], cid, f"EDIT_CONFIG_{service.upper()}") + + if cid not in state.device_configs: + state.device_configs[cid] = {} + state.device_configs[cid][service] = new_config + return jsonify({"success": True}) # --- AGGIORNAMENTO SERVER OTA --- diff --git a/services/mqtt_service.py b/services/mqtt_service.py index 8ea4fb1..99ce02c 100644 --- a/services/mqtt_service.py +++ b/services/mqtt_service.py @@ -333,6 +333,16 @@ def on_message(client, userdata, msg): # 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) + + # --- LETTURA STATO MODI DA TOPIC data/+/MMDVM --- + elif len(parts) == 3 and p0 == 'data' and p2 == 'mmdvm': + try: + cid = parts[1].lower() + data = json.loads(payload) + state.operating_modes[cid] = data + state.notify_update() + except Exception as e: + logger.error(f"Errore parsing MMDVM modes per {cid}: {e}") # --- 8. TRAFFICO VOCE MMDVM (DMR & MODI DIGITALI) --- elif parts[0] == 'mmdvm': diff --git a/static/js/app.js b/static/js/app.js index 057961c..e317219 100644 --- a/static/js/app.js +++ b/static/js/app.js @@ -18,9 +18,18 @@ let mapMarkers = {}; let currentFocusedNode = null; let currentMmdvmConfig = ""; -let currentMmdvmConfigName = ""; +let currentMmdvmConfigAlias = ""; let currentMmdvmServiceName = ""; +// Mappatura Modo -> Gateway service name +const MODE_GATEWAYS = { + 'DMR': ['dmrgateway'], + 'NXDN': ['nxdngateway'], + 'System Fusion': ['ysfgateway'], + 'D-Star': ['dstargateway', 'dstar-gateway'], + 'P25': ['p25gateway'] +}; + function switchView(viewName) { currentFocusedNode = null; document.getElementById('view-focus').style.display = 'none'; @@ -61,7 +70,7 @@ function openNodeFocus(clientId) { document.getElementById('view-focus').style.display = 'block'; window.scrollTo({ top: 0, behavior: 'smooth' }); - document.getElementById('focus-modes-toggles').innerHTML = 'FETCHING CONFIG...'; + document.getElementById('focus-modes-toggles').innerHTML = 'FETCHING CONFIG...'; refreshStates(); refreshLogs(); @@ -222,7 +231,7 @@ function sendTgCommand(clientId, comando) { }); } -// --- LOGICA MODI OPERATIVI (MMDVMHOST.INI) --- +// --- LOGICA MODI OPERATIVI E GATEWAYS --- async function fetchNodeConfigForModes(clientId) { try { const healthObj = globalHealthData[clientId.toLowerCase()]; @@ -232,30 +241,39 @@ async function fetchNodeConfigForModes(clientId) { return; } - // 1. TROVA IL NOME DEL FILE INI ATTIVO ESATTO (Ignorando i profili come _A, _B, ecc) - const activeNames = ['mmdvmhost.ini', 'mmdvm-host.ini', 'mmdvm.ini', 'mmdvm_bridge.ini']; - let confFile = (healthObj.files || healthObj.config_files || []).find(f => activeNames.includes(String(f).toLowerCase())); + let filesList = healthObj.files || healthObj.config_files || []; + let iniFile = filesList.find(f => String(f).toLowerCase().includes('mmdvm') && String(f).toLowerCase().endsWith('.ini')); + if(!iniFile) iniFile = "MMDVMHost.ini"; - if (!confFile) { - confFile = "MMDVMHost.ini"; // Fallback di default - } - currentMmdvmConfigName = confFile; - - // 2. TROVA IL NOME DEL PROCESSO/DEMONE DA RIAVVIARE - let svcName = Object.keys(healthObj.processes || {}).find(k => k.toLowerCase().includes('mmdvm')); - if (!svcName) { - svcName = "mmdvmhost"; // Fallback - } + let svcName = Object.keys(healthObj.processes || {}).find(k => k.toLowerCase().includes('mmdvm')) || "mmdvmhost"; currentMmdvmServiceName = svcName; - const res = await fetch(`/api/config_file/${encodeURIComponent(clientId)}/${encodeURIComponent(confFile)}`); - const data = await res.json(); + let candidates = ["mmdvm", svcName, "mmdvmhost", iniFile, "MMDVMHost.ini"]; + let foundText = null; + + for (let candidate of candidates) { + if(!candidate) continue; + try { + let res = await fetch(`/api/config_file/${encodeURIComponent(clientId)}/${encodeURIComponent(candidate)}`); + let data = await res.json(); + if (data.success && data.data && data.data.raw_text && data.data.raw_text.length > 100) { + foundText = data.data.raw_text; + currentMmdvmConfigAlias = candidate; // Alias con cui salvare + break; + } + } catch(e) {} + } - if (data.success && data.data && data.data.raw_text) { - currentMmdvmConfig = data.data.raw_text; + if (foundText) { + currentMmdvmConfig = foundText; renderModeToggles(clientId); } else { - document.getElementById('focus-modes-toggles').innerHTML = 'CONFIG FETCH FAILED'; + document.getElementById('focus-modes-toggles').innerHTML = ` +
+ [!] CFG MEMORY EMPTY + +
+ `; } } catch (e) { console.error(e); @@ -263,13 +281,16 @@ async function fetchNodeConfigForModes(clientId) { } } -function renderModeToggles(clientId) { +function renderModeToggles(clientId, statusMsg = "") { const role = me.role || ''; const allowedList = String(me.allowed_nodes || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean); let canControl = isAuthenticated && (role === 'admin' || allowedList.includes('all') || allowedList.includes(clientId.toLowerCase())); + let container = document.getElementById('focus-modes-toggles'); + if (!container) return; + if (!canControl) { - document.getElementById('focus-modes-toggles').innerHTML = '[ ACCESS DENIED ]'; + container.innerHTML = '[ ACCESS DENIED ]'; return; } @@ -289,7 +310,6 @@ function renderModeToggles(clientId) { let sectionFound = false; let currentSection = ""; - // Cerca la sezione corretta e la prima occorrenza di "Enable" for (let i = 0; i < lines.length; i++) { let line = lines[i].trim(); if (line.startsWith('[') && line.endsWith(']')) { @@ -307,81 +327,98 @@ function renderModeToggles(clientId) { if (sectionFound) { let btnStyle = enabled - ? `border-color: ${m.color}; color: ${m.color} !important; box-shadow: inset 0 0 8px ${m.color};` - : `border-color: var(--border-light); color: var(--text-muted) !important; opacity: 0.5;`; + ? `border-color: ${m.color}; color: ${m.color} !important; box-shadow: inset 0 0 8px ${m.color}; font-weight: bold;` + : `border-color: var(--border-light); color: var(--text-muted) !important; opacity: 0.4;`; - html += ``; + html += ``; } }); if (html === "") html = 'NO MODES FOUND IN CONFIG'; - document.getElementById('focus-modes-toggles').innerHTML = html; + + if (statusMsg) { + html += `
${statusMsg}
`; + } + + container.innerHTML = html; } function toggleOperatingMode(clientId, section, enable) { const title = currentLang === 'it' ? "[ CAMBIO_MODO ]" : "[ MODE_TOGGLE ]"; const msg = currentLang === 'it' - ? `Vuoi ${enable ? 'ABILITARE' : 'DISABILITARE'} il modo ${section}?

L'operazione salverà il file .ini e riavvierà il demone.` - : `${enable ? 'ENABLE' : 'DISABLE'} mode ${section}?

This will save the INI file and restart the daemon.`; + ? `Vuoi ${enable ? 'ABILITARE' : 'DISABILITARE'} il modo ${section}?

Verranno aggiornati MMDVMHost e il relativo Gateway.` + : `${enable ? 'ENABLE' : 'DISABLE'} mode ${section}?

This will update MMDVMHost and its Gateway.`; customConfirm(title, msg, enable ? "var(--success)" : "var(--danger)", async () => { + // 1. Aggiorna subito il testo locale del file INI let lines = currentMmdvmConfig.split('\n'); let currentSection = ""; - for (let i = 0; i < lines.length; i++) { - let line = lines[i].trim(); - if (line.startsWith('[') && line.endsWith(']')) { - currentSection = line.substring(1, line.length - 1); + let cleanLine = lines[i].trim(); + if (cleanLine.startsWith('[') && cleanLine.endsWith(']')) { + currentSection = cleanLine.substring(1, cleanLine.length - 1); } - if (currentSection.toLowerCase() === section.toLowerCase() && line.toLowerCase().startsWith('enable')) { - let parts = lines[i].split('='); - if(parts.length === 2) { - lines[i] = parts[0] + "=" + (enable ? "1" : "0"); - break; - } + if (currentSection.toLowerCase() === section.toLowerCase() && cleanLine.toLowerCase().startsWith('enable')) { + lines[i] = lines[i].replace(/Enable\s*=\s*[01]/i, `Enable=${enable ? "1" : "0"}`); + break; } } currentMmdvmConfig = lines.join('\n'); - document.getElementById('focus-modes-toggles').innerHTML = 'SAVING & RESTARTING...'; + // 2. Ridisegna SUBITO i pulsanti (così il tasto cambia stato all'istante) e mostra la nota di caricamento + renderModeToggles(clientId, '⏳ SALVATAGGIO & RIAVVIO IN CORSO...'); try { - // 1. Salva file (Usa currentMmdvmConfigName scovato all'inizio) + // 3. Salva il file INI const resSave = await fetch('/api/config_file', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: clientId, - service: currentMmdvmConfigName, + service: currentMmdvmConfigAlias, config_data: { "raw_text": currentMmdvmConfig } }) }); const dataSave = await resSave.json(); + if (!dataSave.success) throw new Error("SAVE ERR: " + dataSave.error); + + // 4. Invia start/stop al Gateway associato + const healthObj = globalHealthData[clientId.toLowerCase()] || {}; + const gwCandidates = MODE_GATEWAYS[section] || []; + const runningProcs = Object.keys(healthObj.processes || {}); + const targetGw = gwCandidates.find(g => runningProcs.some(p => p.toLowerCase() === g.toLowerCase())); - if (!dataSave.success) { - customAlert(t('titleError'), "SAVE ERR: " + esc(dataSave.error), true); - fetchNodeConfigForModes(clientId); - return; + if (targetGw) { + const gwAction = enable ? 'start' : 'stop'; + await fetch('/api/service_control', { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ clientId: clientId, service: targetGw, action: gwAction }) + }); } - // 2. Riavvia servizio (Usa currentMmdvmServiceName) + // 5. Riavvia MMDVMHost const resRst = await fetch('/api/service_control', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ clientId: clientId, service: currentMmdvmServiceName, action: 'restart' }) }); const dataRst = await resRst.json(); + if (!dataRst.success) throw new Error("RESTART ERR: " + dataRst.error); - if (!dataRst.success) { - customAlert(t('titleError'), "RESTART ERR: " + esc(dataRst.error), true); - } + // 6. Conferma avvenuta applicazione senza ricaricare file vecchi + renderModeToggles(clientId, '✅ STATO AGGIORNATO CON SUCCESSO!'); - // Ricarica la configurazione vera dopo 3 secondi per aggiornare la grafica - setTimeout(() => { if (currentFocusedNode === clientId) fetchNodeConfigForModes(clientId); }, 3000); + // Rimuove il messaggio di conferma dopo 3 secondi lasciando i bottoni nello stato nuovo + setTimeout(() => { + if (currentFocusedNode === clientId) { + renderModeToggles(clientId); + } + }, 3000); } catch (e) { console.error(e); - customAlert(t('titleError'), "NETWORK ERROR", true); + customAlert(t('titleError'), String(e), true); fetchNodeConfigForModes(clientId); } }); @@ -645,7 +682,6 @@ async function refreshStates() { let txModeStr = "TX"; let isIdle = telemetryObj.idle === true; - // 1. Usa la logica ORIGINALE, testando solo il contenuto di ts1, ts2 e alt per capire se stiamo trasmettendo. if (telemetryObj.alt && telemetryObj.alt !== "") { let altText = telemetryObj.alt.toUpperCase(); if (altText.includes("NXDN")) { activeModeColor = "var(--success)"; txModeStr = "TX NXDN"; } @@ -671,7 +707,6 @@ async function refreshStates() { cardDiv.dataset.status = isOnline ? 'online' : 'offline'; renderSeen(c, data, isOnline); - // Gestione Avvisi const warns = (data.warnings && data.warnings[c.id.toLowerCase()]) || []; cardDiv.dataset.hasWarn = (warns.length > 0) ? 'true' : 'false'; const diagDiv = document.getElementById(`diag-warn-${c.id}`); @@ -685,7 +720,6 @@ async function refreshStates() { } } - // Intestazione Card const nameSpan = cardDiv.querySelector('.client-name'); const idBadge = cardDiv.querySelector('.badge-id'); const typeBadge = document.getElementById(`type-badge-${c.id}`); @@ -704,7 +738,6 @@ async function refreshStates() { if (typeBadge) typeBadge.style.display = 'none'; } - // Timeslots const tsContainer = document.getElementById(`ts-container-${c.id}`); const ts1Div = document.getElementById(`dmr-ts1-${c.id}`); const ts2Div = document.getElementById(`dmr-ts2-${c.id}`); const altDiv = document.getElementById(`dmr-alt-${c.id}`); if (telemetryObj.alt && telemetryObj.alt !== "") { @@ -804,8 +837,16 @@ async function refreshStates() { if (healthContainer) healthContainer.style.display = 'none'; } + // Logica tollerante per i Gateway in standby (spenti dalla UI) let hasOfflineService = false; - if (healthObj && healthObj.processes) { for (const [svcName, svcStatus] of Object.entries(healthObj.processes)) { if (svcStatus.toLowerCase() !== 'online') { hasOfflineService = true; break; } } } + if (healthObj && healthObj.processes) { + for (const [svcName, svcStatus] of Object.entries(healthObj.processes)) { + let s = svcStatus.toLowerCase(); + if (s !== 'online' && s !== 'standby') { + hasOfflineService = true; break; + } + } + } const warnBadge = document.getElementById(`svc-warn-${c.id}`); const btnSvc = document.getElementById(`btn-svc-${c.id}`); if (warnBadge) warnBadge.style.display = hasOfflineService ? 'block' : 'none'; if (btnSvc) { if (hasOfflineService) { btnSvc.style.borderColor = 'var(--danger)'; btnSvc.style.color = 'var(--danger)'; } else { btnSvc.style.borderColor = 'var(--text-main)'; btnSvc.style.color = 'var(--text-main)'; } } @@ -823,8 +864,6 @@ async function refreshStates() { } } - // 2. LOGICA HANG TIME E RIPRISTINO - // Se l'MMDVM dice "idle" forziamo sempre lo spegnimento di qualsiasi TX visivo e bypassiamo la coda let timeSinceTx = 0; if (isTx && isOnline && !isIdle) { cardDiv.dataset.lastTx = Date.now(); @@ -853,7 +892,6 @@ async function refreshStates() { statusBorder = activeModeColor; } - // Applica i calcoli alla Card Principale if (isOnline) { cardDiv.classList.add('online'); statusDiv.classList.remove('status-offline'); } else { @@ -867,7 +905,6 @@ async function refreshStates() { statusDiv.style.borderColor = statusBorder; } - // Applica i calcoli alla Mini Card in HOME const miniCard = document.getElementById(`mini-card-${c.id}`); const miniStatus = document.getElementById(`mini-status-${c.id}`); if (miniCard && miniStatus) { @@ -917,7 +954,6 @@ async function refreshStates() { } } - // Applica i calcoli al Nodo Singolo (Focus Mode) if (currentFocusedNode === c.id) { let focusStatus = document.getElementById('focus-status'); diff --git a/templates/index.html b/templates/index.html index 3a1bede..fb08bcf 100644 --- a/templates/index.html +++ b/templates/index.html @@ -440,7 +440,7 @@ - +