fiberhome: add prelimunary add ONU support
Signed-off-by: Rodrigo Bertoldo de Sousa Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
ee22ecf693
commit
e5f8bcf546
2 files changed
+244
-115
No files matched your search
+105
-10
@@ -56,10 +56,12 @@ class FiberhomeManager {
|
||||
async conectarUNM2000() {
|
||||
try {
|
||||
if (this.tl1Connection && !this.tl1Connection.destroyed) {
|
||||
console.log('✅ Conexão TL1 já existe e está ativa');
|
||||
this.logger.debug('Conexão TL1 já existe e está ativa');
|
||||
return true;
|
||||
}
|
||||
|
||||
console.log('🔌 Conectando ao UNM2000 via TL1:', this.config.unm2000);
|
||||
this.logger.debug('Conectando ao UNM2000 via TL1', this.config.unm2000);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -72,43 +74,55 @@ class FiberhomeManager {
|
||||
// Handler para dados recebidos
|
||||
this.tl1Connection.on('data', (data) => {
|
||||
dataBuffer += data.toString();
|
||||
console.log('📥 TL1 dados recebidos:', dataBuffer);
|
||||
this.logger.debug('TL1 dados recebidos:', dataBuffer);
|
||||
|
||||
// Verificar se login foi bem-sucedido
|
||||
if (!authenticated && dataBuffer.includes('COMPLD')) {
|
||||
authenticated = true;
|
||||
console.log('✅ Login TL1 bem-sucedido!');
|
||||
this.logger.info('Login TL1 bem-sucedido');
|
||||
resolve(true);
|
||||
} else if (!authenticated && dataBuffer.includes('DENY')) {
|
||||
console.log('❌ Login TL1 negado!');
|
||||
this.logger.error('Login TL1 negado');
|
||||
reject(new Error('Login TL1 negado'));
|
||||
}
|
||||
});
|
||||
|
||||
this.tl1Connection.connect(this.config.unm2000.port, this.config.unm2000.host, () => {
|
||||
console.log('🔗 Socket TL1 conectado, enviando comando de login');
|
||||
this.logger.debug('Socket TL1 conectado, enviando comando de login');
|
||||
|
||||
// Comando de login TL1
|
||||
const loginCommand = `ACT-USER::${this.config.unm2000.username}:${this.commandId++}::${this.config.unm2000.password};`;
|
||||
// Comando de login TL1 - formato correto: LOGIN:::CTAG::UN=username,PWD=password;
|
||||
const loginCommand = `LOGIN:::${this.commandId++}::UN=${this.config.unm2000.username},PWD=${this.config.unm2000.password};`;
|
||||
console.log('📤 Enviando login:', loginCommand);
|
||||
this.tl1Connection.write(loginCommand + '\r\n');
|
||||
|
||||
// Timeout para autenticação
|
||||
setTimeout(() => {
|
||||
if (!authenticated) {
|
||||
this.logger.error('Timeout na autenticação TL1');
|
||||
console.log('⏱️ Timeout na autenticação TL1 (10s). DataBuffer:', dataBuffer);
|
||||
this.logger.error('Timeout na autenticação TL1', { dataBuffer });
|
||||
reject(new Error('Timeout na autenticação TL1'));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
|
||||
this.tl1Connection.on('error', (error) => {
|
||||
console.log('❌ Erro na conexão TL1:', error.message);
|
||||
this.logger.error('Erro na conexão TL1', error);
|
||||
reject(error);
|
||||
});
|
||||
|
||||
this.tl1Connection.on('timeout', () => {
|
||||
console.log('⏱️ Timeout do socket TL1');
|
||||
this.logger.error('Timeout na conexão TL1');
|
||||
reject(new Error('Timeout na conexão TL1'));
|
||||
});
|
||||
|
||||
this.tl1Connection.on('close', () => {
|
||||
console.log('🔌 Conexão TL1 fechada');
|
||||
this.logger.debug('Conexão TL1 fechada');
|
||||
this.tl1Connection = null;
|
||||
});
|
||||
@@ -386,6 +400,7 @@ class FiberhomeManager {
|
||||
*/
|
||||
async descobrirPortaPON(serial) {
|
||||
try {
|
||||
console.log('🔍 Descobrindo porta PON para ONU:', serial);
|
||||
this.logger.debug('Descobrindo porta PON para ONU', { serial });
|
||||
|
||||
// Conectar ao UNM2000
|
||||
@@ -394,18 +409,89 @@ class FiberhomeManager {
|
||||
throw new Error('Não foi possível conectar ao UNM2000');
|
||||
}
|
||||
|
||||
// Buscar em todas as portas PON possíveis (slots 1-20, portas 1-16)
|
||||
for (let slot = 1; slot <= 20; slot++) {
|
||||
for (let porta = 1; porta <= 16; porta++) {
|
||||
let tentativas = 0;
|
||||
const maxTentativas = 320; // Máximo de tentativas (20 slots x 16 portas)
|
||||
|
||||
// Primeiro, tentar listar dispositivos para descobrir o nome correto da OLT
|
||||
console.log('📋 Listando dispositivos OLT...');
|
||||
const listarCmd = `LST-DEVICE:::${this.commandId++}::;`;
|
||||
const dispositivos = await this.executarComandoTL1(listarCmd);
|
||||
|
||||
let oltName = this.config.olt.name; // Fallback para o IP configurado
|
||||
|
||||
if (dispositivos.success && dispositivos.data) {
|
||||
console.log('📋 Resposta LST-DEVICE:', dispositivos.data);
|
||||
|
||||
// Extrair DEVNAME da resposta (formato: AN5516-06_172.16.10.6)
|
||||
const match = dispositivos.data.match(/^([^\s]+)\s+[\d\.]+\s+AN5516/m);
|
||||
if (match && match[1]) {
|
||||
oltName = match[1];
|
||||
console.log(`✅ Nome da OLT descoberto: ${oltName}`);
|
||||
// Atualizar configuração para uso futuro
|
||||
this.config.olt.name = oltName;
|
||||
} else {
|
||||
console.log('⚠️ Não foi possível extrair DEVNAME, usando IP como fallback');
|
||||
}
|
||||
} else {
|
||||
console.log('⚠️ Não foi possível listar dispositivos:', dispositivos.error);
|
||||
}
|
||||
|
||||
// Listar placas PON instaladas para saber quais slots existem
|
||||
console.log('📋 Listando placas PON instaladas...');
|
||||
const listarBoardsCmd = `LST-BOARD::OLTID=${oltName}:${this.commandId++}::;`;
|
||||
const boards = await this.executarComandoTL1(listarBoardsCmd);
|
||||
|
||||
let slotsDisponiveis = [];
|
||||
if (boards.success && boards.data) {
|
||||
console.log('📋 Placas encontradas:', boards.data);
|
||||
|
||||
// Extrair slots das placas GPON (formato BOARDID: 1-1-slot, tipo: GCOB ou GC8B)
|
||||
// Exemplo: "1-1-12 GCOB GPON 16"
|
||||
const ponLines = boards.data.split('\n');
|
||||
for (const line of ponLines) {
|
||||
// Verificar se a linha contém placa GPON
|
||||
if (line.includes('GPON')) {
|
||||
// Extrair BOARDID no formato rack-shelf-slot (ex: 1-1-12)
|
||||
const boardMatch = line.match(/(\d+)-(\d+)-(\d+)\s+(GCOB|GC8B)\s+GPON/);
|
||||
if (boardMatch) {
|
||||
const slot = parseInt(boardMatch[3]); // Pegar o terceiro número (slot)
|
||||
const numPortas = parseInt(line.match(/GPON\s+(\d+)/)[1]); // Número de portas
|
||||
if (!slotsDisponiveis.find(s => s.slot === slot)) {
|
||||
slotsDisponiveis.push({ slot, portas: numPortas });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
slotsDisponiveis.sort((a, b) => a.slot - b.slot);
|
||||
console.log(`✅ Slots PON disponíveis:`, slotsDisponiveis.map(s => `${s.slot} (${s.portas} portas)`).join(', '));
|
||||
}
|
||||
|
||||
if (slotsDisponiveis.length === 0) {
|
||||
console.log('⚠️ Nenhuma placa GPON encontrada, tentando slots 1-20');
|
||||
// Fallback: tentar todos os slots de 1 a 20 com 16 portas
|
||||
slotsDisponiveis = Array.from({length: 20}, (_, i) => ({ slot: i + 1, portas: 16 }));
|
||||
}
|
||||
|
||||
// Buscar em todas as portas PON dos slots disponíveis
|
||||
for (const slotInfo of slotsDisponiveis) {
|
||||
if (tentativas >= maxTentativas) break;
|
||||
|
||||
const { slot, portas } = slotInfo;
|
||||
|
||||
for (let porta = 1; porta <= portas && tentativas < maxTentativas; porta++) {
|
||||
tentativas++;
|
||||
const ponId = `NA-NA-${slot}-${porta}`;
|
||||
const comando = `LST-UNREGONU::OLTID=${this.config.olt.name},PONID=${ponId}:${this.commandId++}::;`;
|
||||
const comando = `LST-UNREGONU::OLTID=${oltName},PONID=${ponId}:${this.commandId++}::;`;
|
||||
|
||||
this.logger.debug('Consultando porta PON', { ponId });
|
||||
console.log(`🔎 Consultando porta PON ${ponId} (slot ${slot}, porta ${porta}/${portas})`);
|
||||
this.logger.debug('Consultando porta PON', { ponId, tentativa: tentativas, oltName });
|
||||
const resultado = await this.executarComandoTL1(comando);
|
||||
|
||||
if (resultado.success && resultado.data) {
|
||||
// Verificar se a ONU está na resposta
|
||||
if (resultado.data.toUpperCase().includes(serial.toUpperCase())) {
|
||||
console.log(`✅ Porta PON descoberta: ${ponId}`);
|
||||
this.logger.info('Porta PON descoberta', { serial, ponId });
|
||||
return {
|
||||
success: true,
|
||||
@@ -414,21 +500,30 @@ class FiberhomeManager {
|
||||
porta
|
||||
};
|
||||
}
|
||||
} else if (!resultado.success) {
|
||||
console.log(`⚠️ Erro ao consultar porta ${ponId}: ${resultado.error}`);
|
||||
// Se o erro for de formato, provavelmente todas as portas vão falhar
|
||||
if (resultado.error && resultado.error.includes('invalid parameter format')) {
|
||||
console.log('❌ Formato de comando inválido, interrompendo busca');
|
||||
throw new Error('Formato de comando LST-UNREGONU inválido. Verifique configuração da OLT.');
|
||||
}
|
||||
}
|
||||
|
||||
// Pequeno delay entre consultas para não sobrecarregar
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
}
|
||||
}
|
||||
|
||||
// ONU não encontrada
|
||||
this.logger.warn('ONU não encontrada em nenhuma porta PON', { serial });
|
||||
console.log(`❌ ONU ${serial} não encontrada após ${tentativas} tentativas`);
|
||||
this.logger.warn('ONU não encontrada em nenhuma porta PON', { serial, tentativas });
|
||||
return {
|
||||
success: false,
|
||||
error: 'ONU não encontrada em nenhuma porta PON. Verifique se a ONU está ligada e descoberta pela OLT.'
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
console.log('❌ Erro ao descobrir porta PON:', error.message);
|
||||
this.logger.error('Erro ao descobrir porta PON', { serial, error: error.message });
|
||||
return {
|
||||
success: false,
|
||||
|
||||
Reference in new issue
Block a user