diagnosticar: fix porta ethernet; sinal; OLT Datacom
Signed-off-by: Rodrigo Bertoldo de Sousa Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
0dbab52aa1
commit
04076fd1b9
2 files changed
+199
-118
No files matched your search
+81
-35
@@ -1045,14 +1045,18 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
const nomePlano = servico.descricao || servico.nome || 'N/A';
|
const nomePlano = servico.descricao || servico.nome || 'N/A';
|
||||||
const endereco = servico.instalacao_endereco || servico.end_rua || null;
|
const endereco = servico.instalacao_endereco || servico.end_rua || null;
|
||||||
const cidade = servico.instalacao_cidade || null;
|
const cidade = servico.instalacao_cidade || null;
|
||||||
|
// Campo base/AP usado para rotear para a OLT correta
|
||||||
|
const baseInfo = servico.base || (servico.id_ap ? `AP ${servico.id_ap}` : null);
|
||||||
|
|
||||||
// Executar consultas em paralelo: Juniper + ONU
|
// Executar consultas em paralelo: Juniper + ONU
|
||||||
|
// No concentrador Juniper usa-se só o usuário (antes do @)
|
||||||
|
const pppoeUser = pppoeLogin ? pppoeLogin.split('@')[0] : null;
|
||||||
const [juniperResult, onuResult] = await Promise.all([
|
const [juniperResult, onuResult] = await Promise.all([
|
||||||
pppoeLogin
|
pppoeUser
|
||||||
? this.ssh.getJuniperSubscriberInfo('juniper', pppoeLogin).catch(e => ({ success: false, error: e.message }))
|
? this.ssh.getJuniperSubscriberInfo('juniper', pppoeUser).catch(e => ({ success: false, error: e.message }))
|
||||||
: Promise.resolve({ success: false, skipped: true }),
|
: Promise.resolve({ success: false, skipped: true }),
|
||||||
serial
|
serial
|
||||||
? this._diagnosticarONU(serial).catch(e => ({ success: false, error: e.message }))
|
? this._diagnosticarONU(serial, baseInfo).catch(e => ({ success: false, error: e.message }))
|
||||||
: Promise.resolve({ success: false, skipped: true })
|
: Promise.resolve({ success: false, skipped: true })
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -1106,7 +1110,7 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
msg += '\n';
|
msg += '\n';
|
||||||
|
|
||||||
if (onuResult.portaEthernet) {
|
if (onuResult.portaEthernet) {
|
||||||
const ethOk = /forward|up|1gbit|100mbit/i.test(onuResult.portaEthernet);
|
const ethOk = /forward|up|active|1gbit|100mbit/i.test(onuResult.portaEthernet);
|
||||||
msg += ` ${ethOk ? '🟢' : '🔴'} Porta Ethernet: ${onuResult.portaEthernet}\n`;
|
msg += ` ${ethOk ? '🟢' : '🔴'} Porta Ethernet: ${onuResult.portaEthernet}\n`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1120,37 +1124,66 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Diagnóstico de ONU: detecta tipo (Datacom/FiberHome) e retorna dados estruturados
|
* Mapeia o campo base/AP do TopSapp para o ID da OLT Datacom (ou 'fiberhome')
|
||||||
*/
|
*/
|
||||||
async _diagnosticarONU(serial) {
|
_resolverOLTporBase(baseInfo) {
|
||||||
const serialUpper = serial.toUpperCase();
|
if (!baseInfo) return null;
|
||||||
|
const b = String(baseInfo).toUpperCase();
|
||||||
if (serialUpper.startsWith('DACM')) {
|
if (/INTERNET\s+FIBRA\s+OPTICA/i.test(b)) return 'fiberhome';
|
||||||
return await this._diagnosticarONUDatacom(serial);
|
if (/COLMEIA/i.test(b)) return 'olt_colmeia';
|
||||||
} else {
|
if (/DITO/i.test(b)) return 'olt_dito';
|
||||||
return await this._diagnosticarONUFiberhome(serial);
|
if (/CANAA\s*2/i.test(b)) return 'olt_canaa2';
|
||||||
}
|
if (/CANAA/i.test(b)) return 'olt_canaa';
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
async _diagnosticarONUDatacom(serial) {
|
/**
|
||||||
const olts = this.ssh.listOLTs();
|
* Diagnóstico de ONU: detecta tipo (Datacom/FiberHome) e retorna dados estruturados
|
||||||
if (olts.length === 0) {
|
* @param {string} serial - Serial da ONU
|
||||||
return { success: false, error: 'Nenhuma OLT Datacom configurada' };
|
* @param {string|null} baseInfo - Campo base/AP do TopSapp para rotear para OLT correta
|
||||||
|
*/
|
||||||
|
async _diagnosticarONU(serial, baseInfo) {
|
||||||
|
const serialUpper = serial.toUpperCase();
|
||||||
|
const oltHint = this._resolverOLTporBase(baseInfo);
|
||||||
|
|
||||||
|
// Usar base description para decidir se é FiberHome
|
||||||
|
if (oltHint === 'fiberhome' ||
|
||||||
|
(!serialUpper.startsWith('DACM') && (serialUpper.startsWith('FHTT') || serialUpper.startsWith('FHGT')))) {
|
||||||
|
return await this._diagnosticarONUFiberhome(serial);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Buscar ONU em todas as OLTs em paralelo
|
return await this._diagnosticarONUDatacom(serial, oltHint);
|
||||||
const searches = olts.map(olt =>
|
}
|
||||||
this.ssh.findOnuBySerial(olt.id, serial)
|
|
||||||
.then(r => ({ ...r, oltId: olt.id, oltName: olt.name }))
|
|
||||||
.catch(() => ({ success: false }))
|
|
||||||
);
|
|
||||||
const results = await Promise.allSettled(searches);
|
|
||||||
|
|
||||||
|
async _diagnosticarONUDatacom(serial, oltIdHint) {
|
||||||
let found = null;
|
let found = null;
|
||||||
for (const r of results) {
|
|
||||||
if (r.status === 'fulfilled' && r.value.success) {
|
// 1. Tentar na OLT indicada pelo campo base/AP do cadastro
|
||||||
found = r.value;
|
if (oltIdHint && this.ssh.equipamentos.has(oltIdHint)) {
|
||||||
break;
|
const r = await this.ssh.findOnuBySerial(oltIdHint, serial).catch(() => null);
|
||||||
|
if (r && r.success) {
|
||||||
|
const olt = this.ssh.equipamentos.get(oltIdHint);
|
||||||
|
found = { ...r, oltId: oltIdHint, oltName: olt.name };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Fallback: buscar em todas as OLTs Datacom
|
||||||
|
if (!found) {
|
||||||
|
const olts = this.ssh.listOLTs();
|
||||||
|
if (olts.length === 0) {
|
||||||
|
return { success: false, error: 'Nenhuma OLT Datacom configurada' };
|
||||||
|
}
|
||||||
|
const searches = olts.map(olt =>
|
||||||
|
this.ssh.findOnuBySerial(olt.id, serial)
|
||||||
|
.then(r => ({ ...r, oltId: olt.id, oltName: olt.name }))
|
||||||
|
.catch(() => ({ success: false }))
|
||||||
|
);
|
||||||
|
const results = await Promise.allSettled(searches);
|
||||||
|
for (const r of results) {
|
||||||
|
if (r.status === 'fulfilled' && r.value.success) {
|
||||||
|
found = r.value;
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1207,21 +1240,34 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
return { success: false, error: resultado.error || 'ONU não encontrada na FiberHome' };
|
return { success: false, error: resultado.error || 'ONU não encontrada na FiberHome' };
|
||||||
}
|
}
|
||||||
|
|
||||||
const portaPrincipal = resultado.portasEthernet && resultado.portasEthernet.length > 0
|
// Preferir porta com dados reais de velocidade; cair para primeira disponível
|
||||||
? resultado.portasEthernet[0]
|
const portas = resultado.portasEthernet || [];
|
||||||
: null;
|
const portaComDados = portas.find(p => p.status !== 'unknown' && p.speed);
|
||||||
|
const portaAtiva = portas.find(p => p.status === 'active');
|
||||||
|
const portaBase = portaComDados || portaAtiva || (portas.length > 0 ? portas[0] : null);
|
||||||
|
|
||||||
|
let portaEthernetStr = null;
|
||||||
|
if (portaBase && portaBase.status !== 'unknown') {
|
||||||
|
const statusLabel = portaBase.status === 'active' ? 'up' : 'down';
|
||||||
|
portaEthernetStr = portaBase.speed
|
||||||
|
? `${statusLabel} — ${portaBase.speed}`
|
||||||
|
: statusLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
// rxPower: retornar null se for 'N/A' para que a UI mostre 'N/A' via fallback
|
||||||
|
const rxPower = resultado.rxPower && resultado.rxPower !== 'N/A' ? resultado.rxPower : null;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
type: 'fiberhome',
|
type: 'fiberhome',
|
||||||
oltName: 'FiberHome',
|
oltName: 'FiberHome AN5516',
|
||||||
slot: resultado.slot,
|
slot: resultado.slot,
|
||||||
pon: resultado.pon,
|
pon: resultado.pon,
|
||||||
onuId: resultado.onuId,
|
onuId: resultado.onuId,
|
||||||
online: resultado.online,
|
online: resultado.online,
|
||||||
rxPower: resultado.rxPower,
|
rxPower,
|
||||||
txPower: resultado.txPower,
|
txPower: resultado.txPower !== 'N/A' ? resultado.txPower : null,
|
||||||
portaEthernet: portaPrincipal ? `${portaPrincipal.status}` : null
|
portaEthernet: portaEthernetStr
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+118
-83
@@ -383,14 +383,14 @@ class FiberhomeManager {
|
|||||||
// Extrair número da ONU da posição encontrada
|
// Extrair número da ONU da posição encontrada
|
||||||
const numeroONU = onuEncontrada.posicao.onuno;
|
const numeroONU = onuEncontrada.posicao.onuno;
|
||||||
|
|
||||||
// Usar comandos TL1 que sabemos que funcionam baseados no manual
|
// Usar comandos TL1 conforme manual (ONUIDTYPE=ONU_NUMBER,ONUID=numero)
|
||||||
const comandosDetalhados = [
|
const comandosDetalhados = [
|
||||||
// Para informações de distância e estado (comando válido do manual)
|
// Estado da ONU (OperState: UP/DOWN/LOS)
|
||||||
`LST-ONUSTATE::OLTID=${oltId},PONID=${ponEncontrada},ONUNO=${numeroONU}:CTAG::;`,
|
`LST-ONUSTATE::OLTID=${oltId},PONID=${ponEncontrada},ONUIDTYPE=ONU_NUMBER,ONUID=${numeroONU}:CTAG::;`,
|
||||||
// Para informações DDM/potência ótica (comando válido do manual)
|
// DDM / potência ótica (RxPower, TxPower)
|
||||||
`LST-OMDDM::OLTID=${oltId},PONID=${ponEncontrada},ONUNO=${numeroONU}:CTAG::;`,
|
`LST-OMDDM::OLTID=${oltId},PONID=${ponEncontrada},ONUIDTYPE=ONU_NUMBER,ONUID=${numeroONU}:CTAG::;`,
|
||||||
// Para informações das portas LAN (comando válido do manual)
|
// Porta LAN 1 (OperStatus, Speed, Duplex)
|
||||||
`LST-ONULANINFO::OLTID=${oltId},PONID=${ponEncontrada},ONUNO=${numeroONU}:CTAG::;`
|
`LST-ONULANINFO::OLTID=${oltId},PONID=${ponEncontrada},ONUIDTYPE=ONU_NUMBER,ONUID=${numeroONU},ONUPORT=NA-NA-NA-1:CTAG::;`
|
||||||
];
|
];
|
||||||
|
|
||||||
this.logger.debug('Executando comandos TL1 detalhados:', comandosDetalhados);
|
this.logger.debug('Executando comandos TL1 detalhados:', comandosDetalhados);
|
||||||
@@ -644,97 +644,132 @@ class FiberhomeManager {
|
|||||||
|
|
||||||
const dados = resposta.response;
|
const dados = resposta.response;
|
||||||
|
|
||||||
// Processar LST-ONUSTATE (distância e estado)
|
// Processar LST-ONUSTATE (estado operacional)
|
||||||
if (resposta.comando && resposta.comando.includes('LST-ONUSTATE')) {
|
if (resposta.comando && resposta.comando.includes('LST-ONUSTATE')) {
|
||||||
// Extrair distância
|
// Verificar estado online/offline — OperState values: UP, DOWN, Power-Off, LOS
|
||||||
const distMatch = dados.match(/DISTANCE\s*=\s*(\d+)/i) ||
|
if (/\bUP\b/.test(dados)) {
|
||||||
dados.match(/RANGING\s*=\s*(\d+)/i);
|
|
||||||
if (distMatch) {
|
|
||||||
resultado.distance = `${distMatch[1]} m`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verificar estado online/offline
|
|
||||||
if (dados.includes('ONLINE') || dados.includes('ACTIVE')) {
|
|
||||||
resultado.online = true;
|
resultado.online = true;
|
||||||
} else if (dados.includes('OFFLINE') || dados.includes('INACTIVE')) {
|
} else if (/\b(DOWN|Power-Off|LOS)\b/i.test(dados)) {
|
||||||
resultado.online = false;
|
resultado.online = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Processar LST-OMDDM (potência ótica)
|
// Processar LST-OMDDM (potência ótica)
|
||||||
|
// Resposta: ONUID RxPower RxPowerR TxPower TxPowerR CurrTxBias ...
|
||||||
if (resposta.comando && resposta.comando.includes('LST-OMDDM')) {
|
if (resposta.comando && resposta.comando.includes('LST-OMDDM')) {
|
||||||
// Verificar se a resposta é válida (deve conter "Optical Power" ou campos de potência)
|
this.logger.debug('LST-OMDDM raw:', dados.substring(0, 500));
|
||||||
if (!dados.includes('RxPower') && !dados.includes('Optical Power')) {
|
|
||||||
this.logger.warn('⚠️ LST-OMDDM retornou formato inesperado, pulando...');
|
// Normalizar CRLF e dividir em linhas
|
||||||
continue;
|
const linhas = dados.replace(/\r/g, '').split('\n');
|
||||||
}
|
|
||||||
|
// Encontrar header: linha que contém 'ONUID' (pode não ter 'RxPower' se quebrou)
|
||||||
// Encontrar o índice da linha do header
|
const headerIndex = linhas.findIndex(l =>
|
||||||
const linhas = dados.split('\n');
|
/\bONUID\b/i.test(l) && (/\bRxPower\b/i.test(l) || /\bTxPower\b/i.test(l))
|
||||||
const headerIndex = linhas.findIndex(l => l.includes('ONUID') && l.includes('RxPower'));
|
|
||||||
|
|
||||||
if (headerIndex === -1) {
|
|
||||||
this.logger.warn('⚠️ Header ONUID/RxPower não encontrado');
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pegar as linhas APÓS o header que contenham dados válidos
|
|
||||||
const linhasDados = linhas.slice(headerIndex + 1).filter(linha =>
|
|
||||||
linha.trim() &&
|
|
||||||
!linha.includes('---') &&
|
|
||||||
linha.match(/[+-]?\d+[,.]?\d+/) && // Deve ter pelo menos um número decimal
|
|
||||||
!linha.includes('FH_') && // Não é cabeçalho da resposta
|
|
||||||
!linha.includes('COMPLD') && // Não é status
|
|
||||||
!linha.includes('total_blocks') // Não é metadado
|
|
||||||
);
|
);
|
||||||
|
|
||||||
this.logger.debug(`📋 LST-OMDDM: ${linhasDados.length} linhas de dados encontradas`);
|
if (headerIndex !== -1) {
|
||||||
|
// Encontrar linha de dados (após o header, ignora traços e metadados)
|
||||||
if (linhasDados.length > 0) {
|
const linhaDados = linhas.slice(headerIndex + 1).find(l =>
|
||||||
// Split por múltiplos espaços ou tabs
|
l.trim() &&
|
||||||
const campos = linhasDados[0].split(/\s+/).filter(c => c);
|
!/^[-\s]+$/.test(l) &&
|
||||||
this.logger.debug(`📊 LST-OMDDM ${campos.length} campos: [${campos.join('] [')}]`);
|
!/COMPLD|total_blocks|block_number|FH_/i.test(l) &&
|
||||||
|
/[+-]?\d+[,.]\d+/.test(l) // linha de dados tem número decimal
|
||||||
// Formato: ONUID RxPower RxPowerR TxPower TxPowerR CurrTxBias CurrTxBiasR
|
);
|
||||||
// Temperature TemperatureR Voltage VoltageR PTxPower PRxPower
|
|
||||||
|
if (linhaDados) {
|
||||||
// RxPower = sinal que a OLT recebe da ONU (uplink) - campo 1
|
// Parsear header e dados para mapear colunas por nome
|
||||||
const rxPower = campos[1]?.replace(',', '.').trim();
|
const headers = linhas[headerIndex].trim().split(/\t|\s{2,}/).map(h => h.trim());
|
||||||
// TxPower = potência transmitida pela OLT - campo 3
|
const valores = linhaDados.trim().split(/\t|\s{2,}/).map(v => v.trim());
|
||||||
const txPower = campos[3]?.replace(',', '.').trim();
|
this.logger.debug(`📊 LST-OMDDM headers: [${headers.join('][')}]`);
|
||||||
|
this.logger.debug(`📊 LST-OMDDM valores: [${valores.join('][')}]`);
|
||||||
// Compensação observada entre UNM2000 e valores brutos TL1
|
|
||||||
const COMPENSACAO_RX = 2.7; // RX: +2.7 dBm
|
const colIdx = (name) => headers.findIndex(h => h.toLowerCase() === name.toLowerCase());
|
||||||
const COMPENSACAO_TX = -2.7; // TX: -2.7 dBm
|
const rxIdx = colIdx('RxPower');
|
||||||
|
const txIdx = colIdx('TxPower');
|
||||||
if (rxPower && rxPower !== '--' && !isNaN(parseFloat(rxPower))) {
|
|
||||||
const rxCompensado = (parseFloat(rxPower) + COMPENSACAO_RX).toFixed(2);
|
// Fallback: se header parse falhou, usar posição fixa (ONUID=0, RxPower=1, TxPower=3)
|
||||||
resultado.rxPower = `${rxCompensado} dBm`;
|
const rxRaw = (rxIdx >= 0 ? valores[rxIdx] : valores[1])?.replace(',', '.');
|
||||||
this.logger.info(`✅ RX Power: ${rxPower} dBm (bruto) → ${rxCompensado} dBm (compensado +${COMPENSACAO_RX})`);
|
const txRaw = (txIdx >= 0 ? valores[txIdx] : valores[3])?.replace(',', '.');
|
||||||
|
|
||||||
|
const COMP_RX = 2.7;
|
||||||
|
const COMP_TX = -2.7;
|
||||||
|
|
||||||
|
if (rxRaw && rxRaw !== '--' && !isNaN(parseFloat(rxRaw))) {
|
||||||
|
resultado.rxPower = `${(parseFloat(rxRaw) + COMP_RX).toFixed(2)} dBm`;
|
||||||
|
this.logger.info(`✅ RxPower bruto=${rxRaw} → ${resultado.rxPower}`);
|
||||||
|
}
|
||||||
|
if (txRaw && txRaw !== '--' && !isNaN(parseFloat(txRaw))) {
|
||||||
|
resultado.txPower = `${(parseFloat(txRaw) + COMP_TX).toFixed(2)} dBm`;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.logger.warn('⚠️ LST-OMDDM: header encontrado mas sem linha de dados numéricos');
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
if (txPower && txPower !== '--' && !isNaN(parseFloat(txPower))) {
|
// Header não encontrado — tentar regex direto no buffer
|
||||||
const txCompensado = (parseFloat(txPower) + COMPENSACAO_TX).toFixed(2);
|
const rxMatch = dados.match(/RxPower[=\s:]+([+-]?\d+[,.]\d+)/i);
|
||||||
resultado.txPower = `${txCompensado} dBm`;
|
if (rxMatch) {
|
||||||
this.logger.info(`✅ TX Power: ${txPower} dBm (bruto) → ${txCompensado} dBm (compensado ${COMPENSACAO_TX})`);
|
const v = parseFloat(rxMatch[1].replace(',', '.')) + 2.7;
|
||||||
|
resultado.rxPower = `${v.toFixed(2)} dBm`;
|
||||||
|
this.logger.info(`✅ RxPower via regex fallback → ${resultado.rxPower}`);
|
||||||
|
} else {
|
||||||
|
this.logger.warn('⚠️ LST-OMDDM: não foi possível extrair RxPower da resposta');
|
||||||
|
this.logger.debug('LST-OMDDM resposta completa:', dados);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Processar LST-ONULANINFO (portas ethernet)
|
// Processar LST-ONULANINFO (porta ethernet)
|
||||||
|
// Resposta: AdminStatus OperStatus DUPLEX PVID VLANPRIORITY SPEED
|
||||||
if (resposta.comando && resposta.comando.includes('LST-ONULANINFO')) {
|
if (resposta.comando && resposta.comando.includes('LST-ONULANINFO')) {
|
||||||
// Extrair informações das portas
|
this.logger.debug('LST-ONULANINFO raw:', dados.substring(0, 400));
|
||||||
const portMatches = dados.matchAll(/PORT\s*=\s*(\d+).*?STATUS\s*=\s*(\w+)/gi);
|
const linhasLan = dados.replace(/\r/g, '').split('\n');
|
||||||
for (const match of portMatches) {
|
|
||||||
const portNum = parseInt(match[1]);
|
// Localizar header: contém AdminStatus ou OperStatus
|
||||||
const status = match[2].toLowerCase();
|
const headerLanIdx = linhasLan.findIndex(l =>
|
||||||
|
/AdminStatus/i.test(l) || /OperStatus/i.test(l)
|
||||||
if (portNum >= 1 && portNum <= 4) {
|
);
|
||||||
if (!resultado.portasEthernet[portNum-1]) {
|
|
||||||
resultado.portasEthernet[portNum-1] = { porta: portNum, status: 'unknown' };
|
if (headerLanIdx !== -1) {
|
||||||
}
|
const headers = linhasLan[headerLanIdx].trim().split(/\t|\s{2,}/).map(h => h.trim());
|
||||||
resultado.portasEthernet[portNum-1].status = status === 'up' ? 'active' :
|
const linhaDados = linhasLan.slice(headerLanIdx + 1).find(l =>
|
||||||
status === 'down' ? 'inactive' : 'unknown';
|
l.trim() && !/^[-\s]+$/.test(l) &&
|
||||||
|
!/COMPLD|total_blocks|block_number/i.test(l)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (linhaDados) {
|
||||||
|
const valores = linhaDados.trim().split(/\t|\s{2,}/).map(v => v.trim());
|
||||||
|
const hLower = headers.map(h => h.toLowerCase());
|
||||||
|
const idxAdm = hLower.findIndex(h => h === 'adminstatus');
|
||||||
|
const idxOper = hLower.findIndex(h => h === 'operstatus');
|
||||||
|
const idxSpeed = hLower.findIndex(h => h === 'speed');
|
||||||
|
const idxDuplex= hLower.findIndex(h => h === 'duplex');
|
||||||
|
|
||||||
|
const operVal = idxOper >= 0 ? valores[idxOper] : valores[1];
|
||||||
|
const speedVal = idxSpeed >= 0 ? valores[idxSpeed] : valores[5];
|
||||||
|
const duplexVal= idxDuplex>= 0 ? valores[idxDuplex]: valores[2];
|
||||||
|
|
||||||
|
const isUp = /^up$/i.test(operVal);
|
||||||
|
const speedClean = speedVal && !/^(--|auto)$/i.test(speedVal) ? speedVal : null;
|
||||||
|
const duplexClean = duplexVal && !/^(--|auto|full|half)$/i.test(duplexVal)
|
||||||
|
? null : (/full/i.test(duplexVal) ? 'Full-Duplex' : duplexVal && /half/i.test(duplexVal) ? 'Half-Duplex' : null);
|
||||||
|
|
||||||
|
const speedLabel = speedClean
|
||||||
|
? (duplexClean ? `${speedClean} ${duplexClean}` : speedClean)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
resultado.portasEthernet[0] = {
|
||||||
|
porta: 1,
|
||||||
|
status: isUp ? 'active' : 'inactive',
|
||||||
|
speed: speedLabel
|
||||||
|
};
|
||||||
|
this.logger.info(`✅ Porta LAN 1: ${isUp ? 'UP' : 'DOWN'} ${speedLabel || ''}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Fallback: tentar extrair OperStatus via regex
|
||||||
|
const upMatch = dados.match(/OperStatus[\s\t]+UP/i) ||
|
||||||
|
dados.match(/(?:^|\t)UP(?:\t|$)/m);
|
||||||
|
if (upMatch !== null) {
|
||||||
|
resultado.portasEthernet[0] = { porta: 1, status: 'active', speed: null };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user