diff --git a/src/fiberhome/manager.js b/src/fiberhome/manager.js index 09607ad..b593736 100644 --- a/src/fiberhome/manager.js +++ b/src/fiberhome/manager.js @@ -410,24 +410,33 @@ class FiberhomeManager { console.log('[TL1-DIAG] Iniciando sequência LST-ONULANINFO...'); const resultadoLAN = await this.executarComandoTL1(comandosDetalhados[2]); console.log(`[TL1-DIAG] LST-ONULANINFO concluído: success=${resultadoLAN.success}`); - + + // LST-ONUSTATE via ONUIDTYPE=MAC para tentar obter LASTONTIME + // (alguns firmwares retornam LASTONTIME apenas nesta forma de consulta) + const cmdEstadoMAC = `LST-ONUSTATE::OLTID=${oltId},PONID=${ponEncontrada},ONUIDTYPE=MAC,ONUID=${serial}:CTAG::;`; + console.log('[TL1-DIAG] Iniciando sequência LST-ONUSTATE (MAC)...'); + const resultadoEstadoMAC = await this.executarComandoTL1(cmdEstadoMAC); + console.log(`[TL1-DIAG] LST-ONUSTATE (MAC) concluído: success=${resultadoEstadoMAC.success}`); + // Adicionar dados coletados onuEncontrada.estadoGeral = resultadoEstado.success ? resultadoEstado.data : null; onuEncontrada.detalhes = resultadoDDM.success ? resultadoDDM.data : null; onuEncontrada.lan = resultadoLAN.success ? resultadoLAN.data : null; - + // Adicionar respostas detalhadas para processamento onuEncontrada.detalhados = [ { comando: comandosDetalhados[0], response: resultadoEstado.data, success: resultadoEstado.success }, { comando: comandosDetalhados[1], response: resultadoDDM.data, success: resultadoDDM.success }, - { comando: comandosDetalhados[2], response: resultadoLAN.data, success: resultadoLAN.success } + { comando: comandosDetalhados[2], response: resultadoLAN.data, success: resultadoLAN.success }, + { comando: cmdEstadoMAC, response: resultadoEstadoMAC.data, success: resultadoEstadoMAC.success } ]; - + // Log dos resultados dos comandos detalhados this.logger.debug('📊 Resultados dos comandos detalhados:', { estado: { success: resultadoEstado.success, length: resultadoEstado.data?.length || 0 }, ddm: { success: resultadoDDM.success, length: resultadoDDM.data?.length || 0 }, - lan: { success: resultadoLAN.success, length: resultadoLAN.data?.length || 0 } + lan: { success: resultadoLAN.success, length: resultadoLAN.data?.length || 0 }, + estadoMAC: { success: resultadoEstadoMAC.success, length: resultadoEstadoMAC.data?.length || 0 } }); // Tentar extrair mais informações dos dados da listagem original @@ -683,58 +692,12 @@ class FiberhomeManager { resultado.online = false; } - // Calcular uptime a partir de LASTOFFTIME (tab-separated) - // O timestamp do servidor (linha de header do TL1) é usado como "agora" - // para evitar divergência de fuso — tudo no horário local do UNM2000. - try { - const linhasState = dados.replace(/\r/g, '').split('\n'); - - // Timestamp do servidor: linha "FH_xxx.xxx.xxx.xxx YYYY-MM-DD HH:MM:SS" - const srvMatch = dados.match(/FH_[\w.]+\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})/); - const serverNow = srvMatch ? new Date(srvMatch[1]) : new Date(); - console.log(`[TL1-DIAG] serverNow="${srvMatch ? srvMatch[1] : 'Date.now()'}"`); - - // Header tab-separado: ONUID \t AdminState \t OperState \t ... \t LASTOFFTIME - const headerLine = linhasState.find(l => /\bONUID\b/i.test(l) && /\bLASTOFFTIME\b/i.test(l)); - if (headerLine) { - const headers = headerLine.trim().split('\t'); - const lastOffIdx = headers.findIndex(h => /LASTOFFTIME/i.test(h)); - console.log(`[TL1-DIAG] LASTOFFTIME col index=${lastOffIdx}`); - - // Linha de dados: tem \tUP\t e não é header/separador - const dataLine = linhasState.find(l => - l.trim() && - !/^[-\s]+$/.test(l) && - !/COMPLD|total_blocks|block_number|list of ONU|FH_/i.test(l) && - /\tUP\t/i.test(l) - ); - console.log(`[TL1-DIAG] dataLine: ${JSON.stringify(dataLine)}`); - - if (dataLine && lastOffIdx !== -1) { - const valores = dataLine.trim().split('\t'); - const lastOffStr = valores[lastOffIdx]; - console.log(`[TL1-DIAG] LASTOFFTIME="${lastOffStr}"`); - - if (lastOffStr && /\d{4}-\d{2}-\d{2}/.test(lastOffStr)) { - const dtOff = new Date(lastOffStr); - const diffMs = serverNow - dtOff; - if (!isNaN(dtOff) && diffMs >= 0) { - const totalMin = Math.floor(diffMs / 60000); - const dias = Math.floor(totalMin / 1440); - const horas = Math.floor((totalMin % 1440) / 60); - const mins = totalMin % 60; - resultado.uptime = dias > 0 - ? `${dias}d ${String(horas).padStart(2,'0')}:${String(mins).padStart(2,'0')}` - : `${String(horas).padStart(2,'0')}:${String(mins).padStart(2,'0')}`; - console.log(`[TL1-DIAG] ✅ uptime="${resultado.uptime}"`); - } - } - } - } else { - console.log('[TL1-DIAG] ⚠️ Header com LASTOFFTIME não encontrado na resposta LST-ONUSTATE'); - } - } catch (e) { - console.log(`[TL1-DIAG] ⚠️ Falha ao calcular uptime: ${e.message}`); + // Extrair timestamp do servidor (horário local do UNM2000) + // para usar como referência no cálculo de uptime + const srvMatch = dados.match(/FH_[\w.]+\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})/); + if (srvMatch && !resultado._serverNow) { + resultado._serverNow = srvMatch[1]; + console.log(`[TL1-DIAG] serverNow="${resultado._serverNow}"`); } } @@ -884,9 +847,64 @@ class FiberhomeManager { } } } + + // Processar LST-ONUSTATE via MAC → busca LASTONTIME para calcular uptime + if (resposta.comando && resposta.comando.includes('LST-ONUSTATE') && resposta.comando.includes('ONUIDTYPE=MAC')) { + try { + const linhasMAC = dados.replace(/\r/g, '').split('\n'); + + // Capturar timestamp do servidor se ainda não temos + if (!resultado._serverNow) { + const srvM = dados.match(/FH_[\w.]+\s+(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})/); + if (srvM) resultado._serverNow = srvM[1]; + } + + // Header tab-separado: procura coluna LASTONTIME + const hdrMAC = linhasMAC.find(l => /\bONUID\b/i.test(l) && /\bLASTONTIME\b/i.test(l)); + console.log(`[TL1-DIAG] MAC LASTONTIME header: ${JSON.stringify(hdrMAC)}`); + + if (hdrMAC) { + const headers = hdrMAC.trim().split('\t'); + const lastOnIdx = headers.findIndex(h => /LASTONTIME/i.test(h)); + const dataLineMAC = linhasMAC.find(l => + l.trim() && + !/^[-\s]+$/.test(l) && + !/COMPLD|total_blocks|block_number|list of ONU|FH_/i.test(l) && + /\tUP\t/i.test(l) + ); + console.log(`[TL1-DIAG] MAC dataLine: ${JSON.stringify(dataLineMAC)}, lastOnIdx=${lastOnIdx}`); + + if (dataLineMAC && lastOnIdx !== -1) { + const vals = dataLineMAC.trim().split('\t'); + const lastOnStr = vals[lastOnIdx]; + console.log(`[TL1-DIAG] LASTONTIME="${lastOnStr}"`); + + if (lastOnStr && /\d{4}-\d{2}-\d{2}/.test(lastOnStr)) { + const serverNow = resultado._serverNow ? new Date(resultado._serverNow) : new Date(); + const dtOn = new Date(lastOnStr); + const diffMs = serverNow - dtOn; + if (!isNaN(dtOn) && diffMs >= 0) { + const totalMin = Math.floor(diffMs / 60000); + const dias = Math.floor(totalMin / 1440); + const horas = Math.floor((totalMin % 1440) / 60); + const mins = totalMin % 60; + resultado.uptime = dias > 0 + ? `${dias}d ${String(horas).padStart(2,'0')}:${String(mins).padStart(2,'0')}` + : `${String(horas).padStart(2,'0')}:${String(mins).padStart(2,'0')}`; + console.log(`[TL1-DIAG] ✅ uptime via LASTONTIME="${resultado.uptime}"`); + } + } + } + } else { + console.log('[TL1-DIAG] ⚠️ LASTONTIME não encontrado na resposta MAC — uptime indisponível'); + } + } catch (e) { + console.log(`[TL1-DIAG] ⚠️ Falha ao calcular uptime via MAC: ${e.message}`); + } + } } } - + // Tentar extrair distância dos dados da listagem (onde já funcionou) if (dadosONU.listagem || dadosONU.dadosOriginais) { const dadosCompletos = dadosONU.listagem || dadosONU.dadosOriginais;