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
1031dc9bd2
2 files changed
+57
-36
No files matched your search
+42
-35
@@ -2,6 +2,7 @@ const NLPProcessor = require('../nlp/processor');
|
|||||||
const SSHManager = require('../ssh/manager');
|
const SSHManager = require('../ssh/manager');
|
||||||
const { TopSappManager } = require('../topsapp');
|
const { TopSappManager } = require('../topsapp');
|
||||||
const FiberhomeManager = require('../fiberhome/manager');
|
const FiberhomeManager = require('../fiberhome/manager');
|
||||||
|
const FiberhomeTL1Manager = require('../fiberhome/manager_tl1');
|
||||||
const config = require('../config/config');
|
const config = require('../config/config');
|
||||||
const logger = require('../utils/logger');
|
const logger = require('../utils/logger');
|
||||||
const DateProcessor = require('../utils/dateProcessor');
|
const DateProcessor = require('../utils/dateProcessor');
|
||||||
@@ -13,6 +14,7 @@ class BotHandler {
|
|||||||
this.ssh = new SSHManager();
|
this.ssh = new SSHManager();
|
||||||
this.topsapp = new TopSappManager();
|
this.topsapp = new TopSappManager();
|
||||||
this.fiberhome = new FiberhomeManager();
|
this.fiberhome = new FiberhomeManager();
|
||||||
|
this.fiberhomeTL1 = new FiberhomeTL1Manager();
|
||||||
this.dateProcessor = new DateProcessor();
|
this.dateProcessor = new DateProcessor();
|
||||||
this.userSessions = new Map(); // Armazena sessões de usuário
|
this.userSessions = new Map(); // Armazena sessões de usuário
|
||||||
this.suporteSessions = new Map(); // Armazena sessões de suporte em andamento
|
this.suporteSessions = new Map(); // Armazena sessões de suporte em andamento
|
||||||
@@ -1081,6 +1083,8 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log(`📝 Criando sessão para usuário ${userId}, serial: ${serialNumber}`);
|
||||||
|
|
||||||
// Criar sessão para coletar informações
|
// Criar sessão para coletar informações
|
||||||
this.userSessions.set(userId, {
|
this.userSessions.set(userId, {
|
||||||
action: 'adicionar_onu_fiberhome_step1',
|
action: 'adicionar_onu_fiberhome_step1',
|
||||||
@@ -1088,6 +1092,8 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
timestamp: Date.now()
|
timestamp: Date.now()
|
||||||
});
|
});
|
||||||
|
|
||||||
|
console.log(`✅ Sessão criada. Sessões ativas:`, this.userSessions.size);
|
||||||
|
|
||||||
// Perguntar o alias/nome do usuário
|
// Perguntar o alias/nome do usuário
|
||||||
await this.bot.sendMessage(chatId,
|
await this.bot.sendMessage(chatId,
|
||||||
`➕ **Adicionar ONU Fiberhome**\n\n` +
|
`➕ **Adicionar ONU Fiberhome**\n\n` +
|
||||||
@@ -1103,6 +1109,10 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
*/
|
*/
|
||||||
async handleUserSessionInput(chatId, text, userId, session) {
|
async handleUserSessionInput(chatId, text, userId, session) {
|
||||||
try {
|
try {
|
||||||
|
console.log(`🔄 Processando input de sessão. Action: ${session.action}, Type: ${session.type}, Text: ${text}`);
|
||||||
|
|
||||||
|
// Verificar se é sessão baseada em action (Fiberhome ONU)
|
||||||
|
if (session.action) {
|
||||||
switch (session.action) {
|
switch (session.action) {
|
||||||
case 'adicionar_onu_fiberhome_step1':
|
case 'adicionar_onu_fiberhome_step1':
|
||||||
// Recebeu o nome do usuário, agora perguntar pelo tipo da ONU
|
// Recebeu o nome do usuário, agora perguntar pelo tipo da ONU
|
||||||
@@ -1119,13 +1129,13 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
};
|
};
|
||||||
|
|
||||||
await this.bot.sendMessage(chatId,
|
await this.bot.sendMessage(chatId,
|
||||||
`📡 **Porta PON:** ${session.portAlias}\n\n` +
|
`👤 **Usuário:** ${session.usuario}\n\n` +
|
||||||
'🔌 Selecione o **tipo da ONU**:',
|
'🔌 Selecione o **tipo da ONU**:',
|
||||||
{ reply_markup: keyboard, parse_mode: 'Markdown' }
|
{ reply_markup: keyboard, parse_mode: 'Markdown' }
|
||||||
);
|
);
|
||||||
break;
|
return;
|
||||||
|
|
||||||
case 'adicionar_onu_fiberhome_step5':
|
case 'adicionar_onu_fiberhome_step3':
|
||||||
// Recebeu confirmação de VLAN customizada
|
// Recebeu confirmação de VLAN customizada
|
||||||
const vlanInput = text.trim();
|
const vlanInput = text.trim();
|
||||||
|
|
||||||
@@ -1146,14 +1156,29 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
|
|
||||||
// Executar adição da ONU
|
// Executar adição da ONU
|
||||||
await this.executarAdicaoOnuFiberhome(chatId, session);
|
await this.executarAdicaoOnuFiberhome(chatId, session);
|
||||||
break;
|
return;
|
||||||
|
|
||||||
default:
|
|
||||||
// Sessão desconhecida, limpar
|
|
||||||
this.userSessions.delete(userId);
|
|
||||||
await this.bot.sendMessage(chatId, '❌ Sessão expirada. Por favor, comece novamente.');
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verificar se é sessão baseada em type (outros fluxos)
|
||||||
|
if (session.type) {
|
||||||
|
switch (session.type) {
|
||||||
|
case 'waiting_custom_command':
|
||||||
|
await this.executeCustomCommand(chatId, session.connectionId, text);
|
||||||
|
this.userSessions.delete(userId);
|
||||||
|
return;
|
||||||
|
|
||||||
|
case 'waiting_username_disconnect':
|
||||||
|
await this.handleDisconnectUser(chatId, text.trim());
|
||||||
|
this.userSessions.delete(userId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Estado desconhecido
|
||||||
|
console.log(`❓ Estado de sessão desconhecido: action=${session.action}, type=${session.type}`);
|
||||||
|
this.userSessions.delete(userId);
|
||||||
|
await this.bot.sendMessage(chatId, '❓ Estado de sessão desconhecido. Tente novamente.');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ Erro ao processar input da sessão:', error);
|
console.error('❌ Erro ao processar input da sessão:', error);
|
||||||
this.userSessions.delete(userId);
|
this.userSessions.delete(userId);
|
||||||
@@ -1179,7 +1204,7 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Executar comando TL1 via Fiberhome Manager
|
// Executar comando TL1 via Fiberhome Manager
|
||||||
const resultado = await this.fiberhome.adicionarOnuFiberhome(
|
const resultado = await this.fiberhomeTL1.adicionarOnuFiberhome(
|
||||||
serial,
|
serial,
|
||||||
usuario,
|
usuario,
|
||||||
vlan,
|
vlan,
|
||||||
@@ -1548,25 +1573,8 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lida com input de usuário durante sessões específicas
|
* MÉTODO REMOVIDO - handleUserSessionInput duplicado foi mesclado acima
|
||||||
*/
|
*/
|
||||||
async handleUserSessionInput(chatId, text, userId, session) {
|
|
||||||
switch (session.type) {
|
|
||||||
case 'waiting_custom_command':
|
|
||||||
await this.executeCustomCommand(chatId, session.connectionId, text);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case 'waiting_username_disconnect':
|
|
||||||
await this.handleDisconnectUser(chatId, text.trim());
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
await this.bot.sendMessage(chatId, '❓ Estado de sessão desconhecido. Tente novamente.');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Limpar sessão
|
|
||||||
this.userSessions.delete(userId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Executa comando personalizado em uma conexão SSH
|
* Executa comando personalizado em uma conexão SSH
|
||||||
@@ -2639,7 +2647,7 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
|
|
||||||
// Recuperar sessão
|
// Recuperar sessão
|
||||||
const session = this.userSessions.get(userId);
|
const session = this.userSessions.get(userId);
|
||||||
if (!session || session.action !== 'adicionar_onu_fiberhome_step4') {
|
if (!session || session.action !== 'adicionar_onu_fiberhome_step2') {
|
||||||
await this.bot.answerCallbackQuery(callbackQuery.id, '❌ Sessão expirada');
|
await this.bot.answerCallbackQuery(callbackQuery.id, '❌ Sessão expirada');
|
||||||
await this.bot.sendMessage(chatId, '❌ Sessão expirada. Por favor, comece novamente.');
|
await this.bot.sendMessage(chatId, '❌ Sessão expirada. Por favor, comece novamente.');
|
||||||
this.userSessions.delete(userId);
|
this.userSessions.delete(userId);
|
||||||
@@ -2647,6 +2655,8 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
}
|
}
|
||||||
|
|
||||||
session.onuType = onuType;
|
session.onuType = onuType;
|
||||||
|
session.action = 'adicionar_onu_fiberhome_step3';
|
||||||
|
this.userSessions.set(userId, session);
|
||||||
|
|
||||||
await this.bot.answerCallbackQuery(callbackQuery.id);
|
await this.bot.answerCallbackQuery(callbackQuery.id);
|
||||||
|
|
||||||
@@ -2681,7 +2691,7 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
|
|
||||||
// Recuperar sessão
|
// Recuperar sessão
|
||||||
const session = this.userSessions.get(userId);
|
const session = this.userSessions.get(userId);
|
||||||
if (!session || session.action !== 'adicionar_onu_fiberhome_step2') {
|
if (!session || session.action !== 'adicionar_onu_fiberhome_step3') {
|
||||||
await this.bot.answerCallbackQuery(callbackQuery.id, '❌ Sessão expirada');
|
await this.bot.answerCallbackQuery(callbackQuery.id, '❌ Sessão expirada');
|
||||||
await this.bot.sendMessage(chatId, '❌ Sessão expirada. Por favor, comece novamente.');
|
await this.bot.sendMessage(chatId, '❌ Sessão expirada. Por favor, comece novamente.');
|
||||||
this.userSessions.delete(userId);
|
this.userSessions.delete(userId);
|
||||||
@@ -2701,10 +2711,7 @@ Digite /help para ver todos os comandos disponíveis!
|
|||||||
await this.executarAdicaoOnuFiberhome(chatId, session);
|
await this.executarAdicaoOnuFiberhome(chatId, session);
|
||||||
|
|
||||||
} else if (data === 'fh_vlan_custom') {
|
} else if (data === 'fh_vlan_custom') {
|
||||||
// Pedir VLAN customizada
|
// Pedir VLAN customizada - manter sessão no step3 para receber input do usuário
|
||||||
session.action = 'adicionar_onu_fiberhome_step3';
|
|
||||||
this.userSessions.set(userId, session);
|
|
||||||
|
|
||||||
await this.bot.editMessageText(
|
await this.bot.editMessageText(
|
||||||
`🏷️ **VLAN Customizada**\n\n` +
|
`🏷️ **VLAN Customizada**\n\n` +
|
||||||
`Digite o número da VLAN que deseja usar (1-4094):`,
|
`Digite o número da VLAN que deseja usar (1-4094):`,
|
||||||
|
|||||||
@@ -56,10 +56,12 @@ class FiberhomeManager {
|
|||||||
async conectarUNM2000() {
|
async conectarUNM2000() {
|
||||||
try {
|
try {
|
||||||
if (this.tl1Connection && !this.tl1Connection.destroyed) {
|
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');
|
this.logger.debug('Conexão TL1 já existe e está ativa');
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log('🔌 Conectando ao UNM2000 via TL1:', this.config.unm2000);
|
||||||
this.logger.debug('Conectando ao UNM2000 via TL1', this.config.unm2000);
|
this.logger.debug('Conectando ao UNM2000 via TL1', this.config.unm2000);
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
@@ -72,43 +74,55 @@ class FiberhomeManager {
|
|||||||
// Handler para dados recebidos
|
// Handler para dados recebidos
|
||||||
this.tl1Connection.on('data', (data) => {
|
this.tl1Connection.on('data', (data) => {
|
||||||
dataBuffer += data.toString();
|
dataBuffer += data.toString();
|
||||||
|
console.log('📥 TL1 dados recebidos:', dataBuffer);
|
||||||
this.logger.debug('TL1 dados recebidos:', dataBuffer);
|
this.logger.debug('TL1 dados recebidos:', dataBuffer);
|
||||||
|
|
||||||
// Verificar se login foi bem-sucedido
|
// Verificar se login foi bem-sucedido
|
||||||
if (!authenticated && dataBuffer.includes('COMPLD')) {
|
if (!authenticated && dataBuffer.includes('COMPLD')) {
|
||||||
authenticated = true;
|
authenticated = true;
|
||||||
|
console.log('✅ Login TL1 bem-sucedido!');
|
||||||
this.logger.info('Login TL1 bem-sucedido');
|
this.logger.info('Login TL1 bem-sucedido');
|
||||||
resolve(true);
|
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, () => {
|
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');
|
this.logger.debug('Socket TL1 conectado, enviando comando de login');
|
||||||
|
|
||||||
// Comando de login TL1
|
// Comando de login TL1
|
||||||
const loginCommand = `ACT-USER::${this.config.unm2000.username}:${this.commandId++}::${this.config.unm2000.password};`;
|
const loginCommand = `ACT-USER::${this.config.unm2000.username}:${this.commandId++}::${this.config.unm2000.password};`;
|
||||||
|
console.log('📤 Enviando login:', loginCommand);
|
||||||
this.tl1Connection.write(loginCommand + '\r\n');
|
this.tl1Connection.write(loginCommand + '\r\n');
|
||||||
|
|
||||||
// Timeout para autenticação
|
// Timeout para autenticação
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (!authenticated) {
|
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'));
|
reject(new Error('Timeout na autenticação TL1'));
|
||||||
}
|
}
|
||||||
}, 10000);
|
}, 10000);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.tl1Connection.on('error', (error) => {
|
this.tl1Connection.on('error', (error) => {
|
||||||
|
console.log('❌ Erro na conexão TL1:', error.message);
|
||||||
this.logger.error('Erro na conexão TL1', error);
|
this.logger.error('Erro na conexão TL1', error);
|
||||||
reject(error);
|
reject(error);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.tl1Connection.on('timeout', () => {
|
this.tl1Connection.on('timeout', () => {
|
||||||
|
console.log('⏱️ Timeout do socket TL1');
|
||||||
this.logger.error('Timeout na conexão TL1');
|
this.logger.error('Timeout na conexão TL1');
|
||||||
reject(new Error('Timeout na conexão TL1'));
|
reject(new Error('Timeout na conexão TL1'));
|
||||||
});
|
});
|
||||||
|
|
||||||
this.tl1Connection.on('close', () => {
|
this.tl1Connection.on('close', () => {
|
||||||
|
console.log('🔌 Conexão TL1 fechada');
|
||||||
this.logger.debug('Conexão TL1 fechada');
|
this.logger.debug('Conexão TL1 fechada');
|
||||||
this.tl1Connection = null;
|
this.tl1Connection = null;
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in new issue
Block a user