From ee22ecf693ea0f175163e96eb0fcc470bf9202d6 Mon Sep 17 00:00:00 2001 From: Rodrigo Bertoldo de Sousa Martins Date: Tue, 10 Feb 2026 18:27:40 -0300 Subject: [PATCH] fiberhome: add prelimunary add ONU support Signed-off-by: Rodrigo Bertoldo de Sousa Martins --- FIBERHOME-TL1-ADD-ONU.md | 250 ++++++++++++++++++++++++++++++++ src/bot/handler.js | 273 +++++++++++++++++++++++++++++++++++ src/fiberhome/manager_tl1.js | 174 ++++++++++++++++++++++ src/nlp/processor.js | 27 ++++ 4 files changed, 724 insertions(+) create mode 100644 FIBERHOME-TL1-ADD-ONU.md diff --git a/FIBERHOME-TL1-ADD-ONU.md b/FIBERHOME-TL1-ADD-ONU.md new file mode 100644 index 0000000..d0240f4 --- /dev/null +++ b/FIBERHOME-TL1-ADD-ONU.md @@ -0,0 +1,250 @@ +# Funcionalidade: Adicionar ONU Fiberhome via TL1 + +## Descrição + +Esta funcionalidade permite adicionar ONUs Fiberhome via protocolo TL1, configurando automaticamente todos os parâmetros necessários através do UNM2000. + +## Comando + +``` +adicionar onu fiberhome SERIAL +``` + +ou + +``` +fiberhome onu SERIAL +``` + +**Exemplo:** +``` +adicionar onu fiberhome FHTT12345678 +``` + +## Fluxo de Execução + +O processo de adição é **interativo** e coleta as seguintes informações: + +### 1. Nome/Alias do Usuário +- O bot solicita que você digite o nome ou alias do usuário +- Este nome será usado como identificador da ONU no sistema +- **Exemplo:** `joao_silva`, `cliente123` + +### 2. Descoberta Automática da Porta PON +- O sistema busca automaticamente em todas as portas PON (slots 1-20, portas 1-16) +- Utiliza o comando `LST-UNREGONU` para encontrar a ONU descoberta +- A ONU deve estar **ligada e descoberta** pela OLT + +### 3. Tipo da ONU +- Selecione o tipo da ONU via botões: + - **AN5506-02-B** (2 portas Ethernet) + - **AN5506-01-A** (1 porta Ethernet) + +### 4. VLAN +- Escolha entre: + - **VLAN padrão 1002** (recomendado) + - **VLAN customizada** (digite o número de 1 a 4094) + +## Comandos TL1 Executados + +O sistema executa automaticamente a seguinte sequência de comandos TL1: + +### 0. LST-UNREGONU - Descoberta da Porta PON +```tl1 +LST-UNREGONU::OLTID=131.0.192.9,PONID=NA-NA-[slot]-[porta]:CTAG::; +``` +- Busca em todas as portas PON (slots 1-20, portas 1-16) +- Identifica em qual porta a ONU está descoberta + +### 1. ADD-ONU - Autenticação da ONU +```tl1 +ADD-ONU::OLTID=131.0.192.9,PONID=NA-NA-[portaalias]:CTAG::AUTHTYPE=MAC,ONUTYPE=[tipo],NAME=[usuario],ONUID=[serial]; +``` + +### 2. SET-WANSERVICE - Configuração de WAN Services + +**Para ONU de 2 portas (AN5506-02-B):** +```tl1 +SET-WANSERVICE::OLTID=131.0.192.9,PONID=NA-NA-[portaalias],ONUIDTYPE=MAC,ONUID=[serial]:CTAG::STATUS=1,MODE=2,CONNTYPE=1,VLAN=[vlan],COS=0,QOS=2,UPORT=1; + +SET-WANSERVICE::OLTID=131.0.192.9,PONID=NA-NA-[portaalias],ONUIDTYPE=MAC,ONUID=[serial]:CTAG::STATUS=1,MODE=2,CONNTYPE=1,VLAN=[vlan],COS=0,QOS=2,UPORT=2; +``` + +**Para ONU de 1 porta (AN5506-01-A):** +```tl1 +SET-WANSERVICE::OLTID=131.0.192.9,PONID=NA-NA-[portaalias],ONUIDTYPE=MAC,ONUID=[serial]:CTAG::STATUS=1,MODE=2,CONNTYPE=1,VLAN=[vlan],COS=0,QOS=2,UPORT=1; +``` + +### 3. CFG-WEBADMINISTRATOR - Configuração de Autenticação Web +```tl1 +CFG-WEBADMINISTRATOR::OLTID=131.0.192.9,PONID=NA-NA-[portaalias],ONUIDTYPE=MAC,ONUID=[serial]:CTAG::WEBUSERNAME=admin,WEBPASSWORD=clicknet10; +``` + +### 4. RESET-ONU - Reinicialização da ONU +```tl1 +RESET-ONU::OLTID=131.0.192.9,PONID=NA-NA-[portaalias],ONUIDTYPE=MAC,ONUID=[serial]:CTAG::; +``` + +## Parâmetros de Configuração + +### Autenticação +- **Tipo:** MAC (autenticação por endereço MAC) +- **Serial:** Fornecido pelo usuário (formato: FHTTXXXXXXXX) + +### WAN Service +- **STATUS:** 1 (ativo) +- **MODE:** 2 (INTERNET) +- **CONNTYPE:** 1 (Bridge) +- **VLAN:** Configurável (padrão: 1002) +- **COS:** 0 +- **QOS:** 2 (desabilitado) +- **UPORT:** 1 ou 2 (dependendo da porta) + +### Autenticação Web +- **Username:** admin (fixo) +- **Password:** clicknet10 (fixo) + +## Mensagens de Retorno + +### Sucesso +``` +✅ ONU Fiberhome Adicionada com Sucesso! + +👤 Usuário: joao_silva +🏢 OLT: 131.0.192.9 +📡 Porta descoberta: Slot 7, PON 1 +📱 Serial: FHTT12345678 +🔌 Tipo: AN5506-02-B +🏷️ VLAN: 1002 +⚙️ Portas configuradas: 2 + +🔐 Login Web: admin / clicknet10 + +⚡ A ONU foi reiniciada e estará disponível em alguns instantes. +``` + +### Erro +``` +❌ Erro ao adicionar ONU Fiberhome + +⚠️ [Mensagem de erro detalhada] +``` + +## Estrutura de Código + +### Arquivos Modificados/Criados + +1. **src/fiberhome/manager_tl1.js** + - Método `descobrirPortaPON()`: Busca ONU nas portas PON + - Método `adicionarOnuFiberhome()`: Executa sequência de comandos TL1 + - Configuração da OLT única (131.0.192.9) + +2. **src/nlp/processor.js** + - Adicionado reconhecimento de padrões para comando Fiberhome + +3. **src/bot/handler.js** + - `handleAdicionarOnuFiberhome()`: Inicia processo interativo + - `handleUserSessionInput()`: Processa inputs do usuário + - `executarAdicaoOnuFiberhome()`: Executa adição da ONU + - `handleFiberhomeOnuTypeCallback()`: Callback para tipo de ONU + - `handleFiberhomeVlanCallback()`: Callback para VLAN + +## Sessões de Usuário + +O sistema utiliza sessões para armazenar temporariamente os dados coletados: + +```javascript +{ + action: 'adicionar_onu_fiberhome_step1|2|3', + serial: 'FHTT12345678', + usuario: 'joao_silva', + onuType: 'AN5506-02-B', + vlan: 1002, + timestamp: Date.now() +} +``` + +### Fluxo de Steps + +1. **step1**: Aguardando nome do usuário +2. **step2**: Aguardando seleção do tipo de ONU e VLAN +3. **step3**: Aguardando VLAN customizada (se aplicável) + +## Segurança + +- Apenas usuários autorizados podem executar o comando +- Validação de VLAN (1-4094) +- Timeout de sessão para evitar sessões orfãs +- Logging detalhado de todas as operações + +## Logs + +Todos os passos são registrados no logger: + +```javascript +logger.info('Iniciando adição de ONU Fiberhome via TL1', { nameOlt, portAlias, serial, usuario, vlan, onuType }); +logger.debug('Executando ADD-ONU', { comando }); +logger.warn('Aviso ao configurar WAN porta', { erro }); +logger.error('Erro ao adicionar ONU Fiberhome', { erro }); +``` + +## Exemplos de Uso + +### Exemplo 1: ONU de 2 portas com VLAN padrão +``` +Usuário: adicionar onu fiberhome FHTT12345678 +Bot: 👤 Digite o nome/alias do usuário: +Usuário: cliente_123 +Bot: 🔌 Selecione o tipo da ONU: +[Usuário seleciona: AN5506-02-B] +Bot: 🏷️ VLAN: A VLAN padrão é 1002... +[Usuário seleciona: Usar VLAN 1002 (padrão)] +Bot: ⏳ Adicionando ONU Fiberhome... + 🔍 Descobrindo porta PON automaticamente... +Bot: ✅ ONU Fiberhome Adicionada com Sucesso! + 📡 Porta descoberta: Slot 7, PON 1 +``` + +### Exemplo 2: ONU de 1 porta com VLAN customizada +``` +Usuário: fiberhome onu FHTT87654321 +Bot: 👤 Digite o nome/alias do usuário: +Usuário: empresa_xyz +Bot: 🔌 Selecione o tipo da ONU: +[Usuário seleciona: AN5506-01-A] +Bot: 🏷️ VLAN: A VLAN padrão é 1002... +[Usuário seleciona: Usar outra VLAN] +Bot: Digite o número da VLAN (1-4094): +Usuário: 603 +Bot: ⏳ Adicionando ONU Fiberhome... + 🔍 Descobrindo porta PON automaticamente... +Bot: ✅ ONU Fiberhome Adicionada com Sucesso! + 📡 Porta descoberta: Slot 3, PON 4 +``` + +## Troubleshooting + +### Erro: "Não foi possível conectar ao UNM2000" +- Verificar conectividade de rede com 131.0.192.9:3337 +- Verificar credenciais de login TL1 + +### Erro: "ONU não encontrada em nenhuma porta PON" +- Verificar se a ONU está **ligada** +- Verificar se a ONU está **descoberta** pela OLT +- Verificar se o serial está correto (formato: FHTTXXXXXXXX) +- A ONU precisa estar no estado "unregistered" para ser descoberta + +### Erro: "Falha ao adicionar ONU" +- Verificar se a ONU já não está cadastrada +- Verificar se há espaço disponível na porta PON +- Verificar logs do UNM2000 + +### Erro: "Sessão expirada" +- Reiniciar o processo com o comando inicial +- Não demorar muito entre as respostas +- Completar o fluxo sem interrupções + +## Referências + +- Manual TL1 Fiberhome: `material/fiberhometl1.txt` +- Documentação UNM2000: Seção 5.1 "ONU Configuration (FTTH)" diff --git a/src/bot/handler.js b/src/bot/handler.js index e9619ee..747b69a 100644 --- a/src/bot/handler.js +++ b/src/bot/handler.js @@ -92,6 +92,7 @@ class BotHandler { */ async executeAction(chatId, intent, user) { const { action, target, confidence, type } = intent; + const userId = user.id; // Extrair userId do objeto user // Se a confiança é muito baixa, pedir esclarecimento if (confidence < 0.3 && action) { @@ -178,6 +179,11 @@ class BotHandler { await this.handleAdicionarOnuVlan(chatId, target, intent.vlanId); break; + case 'adicionar_onu_fiberhome': + console.log(`➕ Executando handleAdicionarOnuFiberhome com target: ${target}`); + await this.handleAdicionarOnuFiberhome(chatId, target, userId); + break; + case 'buscar_cliente': console.log(`🔍 Executando handleBuscarCliente com target: ${target}`); await this.handleBuscarCliente(chatId, target); @@ -314,6 +320,7 @@ Digite /help para ver todos os comandos disponíveis! 📡 **OLT/ONU:** • "ver sinal DACM91569513" • "adicionar onu SERIAL" +• "adicionar onu fiberhome SERIAL" • "remover onu SERIAL" � **JUNIPER:** @@ -411,6 +418,20 @@ Digite /help para ver todos os comandos disponíveis! • "add onu vlan 700 ABCD12345678" • "adicionar vlan 603 SERIAL_NUMBER" +**➕ ADICIONAR ONU FIBERHOME VIA TL1:** +• "adicionar onu fiberhome FHTT12345678" +• "fiberhome onu FHTT12345678" +• Processo interativo com: + - Nome/alias do usuário + - Nome da OLT + - Porta PON (ex: 7-1) + - Tipo da ONU (AN5506-02-B ou AN5506-01-A) + - VLAN (padrão: 1002) +• Configura automaticamente: + - WAN Services + - Login Web (admin/clicknet10) + - Reinicia a ONU + **🗑️ REMOVER ONU:** • "remover onu DACM91569513" • "deletar ABCD12345678" @@ -1047,6 +1068,156 @@ Digite /help para ver todos os comandos disponíveis! ); } + /** + * Comando para adicionar ONU Fiberhome via TL1 + */ + async handleAdicionarOnuFiberhome(chatId, serialNumber, userId) { + if (!serialNumber) { + await this.bot.sendMessage(chatId, + '❌ Por favor, informe o serial da ONU Fiberhome.\n\n' + + 'Exemplo: `adicionar onu fiberhome FHTT12345678`', + { parse_mode: 'Markdown' } + ); + return; + } + + // Criar sessão para coletar informações + this.userSessions.set(userId, { + action: 'adicionar_onu_fiberhome_step1', + serial: serialNumber, + timestamp: Date.now() + }); + + // Perguntar o alias/nome do usuário + await this.bot.sendMessage(chatId, + `➕ **Adicionar ONU Fiberhome**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🔍 A porta PON será descoberta automaticamente\n\n` + + '👤 Digite o **nome/alias** do usuário:', + { parse_mode: 'Markdown' } + ); + } + + /** + * Processar input do usuário durante sessões + */ + async handleUserSessionInput(chatId, text, userId, session) { + try { + switch (session.action) { + case 'adicionar_onu_fiberhome_step1': + // Recebeu o nome do usuário, agora perguntar pelo tipo da ONU + session.usuario = text.trim(); + session.action = 'adicionar_onu_fiberhome_step2'; + this.userSessions.set(userId, session); + + const keyboard = { + inline_keyboard: [ + [{ text: '🔌 AN5506-02-B (2 portas)', callback_data: 'fh_onu_type_AN5506-02-B' }], + [{ text: '🔌 AN5506-01-A (1 porta)', callback_data: 'fh_onu_type_AN5506-01-A' }], + [{ text: '❌ Cancelar', callback_data: 'cancel_action' }] + ] + }; + + await this.bot.sendMessage(chatId, + `📡 **Porta PON:** ${session.portAlias}\n\n` + + '🔌 Selecione o **tipo da ONU**:', + { reply_markup: keyboard, parse_mode: 'Markdown' } + ); + break; + + case 'adicionar_onu_fiberhome_step5': + // Recebeu confirmação de VLAN customizada + const vlanInput = text.trim(); + + if (vlanInput && !isNaN(vlanInput)) { + const vlan = parseInt(vlanInput); + if (vlan >= 1 && vlan <= 4094) { + session.vlan = vlan; + } else { + await this.bot.sendMessage(chatId, '❌ VLAN inválida. Usando VLAN padrão 1002.'); + session.vlan = 1002; + } + } else { + session.vlan = 1002; + } + + // Limpar sessão + this.userSessions.delete(userId); + + // Executar adição da ONU + await this.executarAdicaoOnuFiberhome(chatId, session); + break; + + default: + // Sessão desconhecida, limpar + this.userSessions.delete(userId); + await this.bot.sendMessage(chatId, '❌ Sessão expirada. Por favor, comece novamente.'); + break; + } + } catch (error) { + console.error('❌ Erro ao processar input da sessão:', error); + this.userSessions.delete(userId); + await this.bot.sendMessage(chatId, '❌ Erro ao processar sua resposta. Tente novamente.'); + } + } + + /** + * Executar adição da ONU Fiberhome + */ + async executarAdicaoOnuFiberhome(chatId, session) { + try { + const { serial, usuario, vlan, onuType } = session; + + await this.bot.sendMessage(chatId, + `⏳ Adicionando ONU Fiberhome...\n\n` + + `🔍 Descobrindo porta PON automaticamente...\n` + + `👤 **Usuário:** ${usuario}\n` + + `📱 **Serial:** ${serial}\n` + + `🔌 **Tipo:** ${onuType}\n` + + `🏷️ **VLAN:** ${vlan}`, + { parse_mode: 'Markdown' } + ); + + // Executar comando TL1 via Fiberhome Manager + const resultado = await this.fiberhome.adicionarOnuFiberhome( + serial, + usuario, + vlan, + onuType + ); + + if (resultado.success) { + await this.bot.sendMessage(chatId, + `✅ **ONU Fiberhome Adicionada com Sucesso!**\n\n` + + `👤 **Usuário:** ${usuario}\n` + + `🏢 **OLT:** ${resultado.details.olt}\n` + + `📡 **Porta descoberta:** Slot ${resultado.details.slot}, PON ${resultado.details.ponPort}\n` + + `📱 **Serial:** ${serial}\n` + + `🔌 **Tipo:** ${onuType}\n` + + `🏷️ **VLAN:** ${vlan}\n` + + `⚙️ **Portas configuradas:** ${resultado.details.portas}\n\n` + + `🔐 **Login Web:** admin / clicknet10\n\n` + + `⚡ A ONU foi reiniciada e estará disponível em alguns instantes.`, + { parse_mode: 'Markdown' } + ); + } else { + await this.bot.sendMessage(chatId, + `❌ **Erro ao adicionar ONU Fiberhome**\n\n` + + `⚠️ ${resultado.error}`, + { parse_mode: 'Markdown' } + ); + } + + } catch (error) { + console.error('❌ Erro ao executar adição de ONU Fiberhome:', error); + await this.bot.sendMessage(chatId, + `❌ **Erro ao adicionar ONU Fiberhome**\n\n` + + `⚠️ ${error.message}`, + { parse_mode: 'Markdown' } + ); + } + } + /** * Comando não reconhecido */ @@ -1158,6 +1329,12 @@ Digite /help para ver todos os comandos disponíveis! } else if (data.startsWith('add_onu_')) { console.log(`🔍 Chamando handleAddOnuCallback`); await this.handleAddOnuCallback(callbackQuery, data); + } else if (data.startsWith('fh_onu_type_')) { + console.log(`🔍 Chamando handleFiberhomeOnuTypeCallback`); + await this.handleFiberhomeOnuTypeCallback(callbackQuery, data); + } else if (data.startsWith('fh_vlan_')) { + console.log(`🔍 Chamando handleFiberhomeVlanCallback`); + await this.handleFiberhomeVlanCallback(callbackQuery, data); } else if (data.startsWith('fiberhome_details_')) { console.log(`🔍 Condição fiberhome_details_ atendida`); const serialNumber = data.replace('fiberhome_details_', ''); @@ -1180,6 +1357,12 @@ Digite /help para ver todos os comandos disponíveis! await this.bot.answerCallbackQuery(callbackQuery.id); } else if (data === 'cancel_action') { await this.bot.answerCallbackQuery(callbackQuery.id, 'Ação cancelada'); + + // Limpar sessão do usuário se existir + if (this.userSessions.has(userId)) { + this.userSessions.delete(userId); + } + await this.bot.editMessageText('❌ Ação cancelada.', { chat_id: chatId, message_id: callbackQuery.message.message_id @@ -2444,6 +2627,96 @@ Digite /help para ver todos os comandos disponíveis! } } + /** + * Handle callback para tipo de ONU Fiberhome + */ + async handleFiberhomeOnuTypeCallback(callbackQuery, data) { + const chatId = callbackQuery.message.chat.id; + const userId = callbackQuery.from.id; + + // Formato: fh_onu_type_AN5506-02-B ou fh_onu_type_AN5506-01-A + const onuType = data.replace('fh_onu_type_', ''); + + // Recuperar sessão + const session = this.userSessions.get(userId); + if (!session || session.action !== 'adicionar_onu_fiberhome_step4') { + await this.bot.answerCallbackQuery(callbackQuery.id, '❌ Sessão expirada'); + await this.bot.sendMessage(chatId, '❌ Sessão expirada. Por favor, comece novamente.'); + this.userSessions.delete(userId); + return; + } + + session.onuType = onuType; + + await this.bot.answerCallbackQuery(callbackQuery.id); + + // Perguntar sobre VLAN + const keyboard = { + inline_keyboard: [ + [{ text: '✅ Usar VLAN 1002 (padrão)', callback_data: 'fh_vlan_1002' }], + [{ text: '🔧 Usar outra VLAN', callback_data: 'fh_vlan_custom' }], + [{ text: '❌ Cancelar', callback_data: 'cancel_action' }] + ] + }; + + await this.bot.editMessageText( + `🔌 **Tipo da ONU:** ${onuType}\n\n` + + `🏷️ **VLAN:**\n` + + `A VLAN padrão é 1002. Deseja usar esta VLAN ou configurar outra?`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + reply_markup: keyboard, + parse_mode: 'Markdown' + } + ); + } + + /** + * Handle callback para VLAN Fiberhome + */ + async handleFiberhomeVlanCallback(callbackQuery, data) { + const chatId = callbackQuery.message.chat.id; + const userId = callbackQuery.from.id; + + // Recuperar sessão + const session = this.userSessions.get(userId); + if (!session || session.action !== 'adicionar_onu_fiberhome_step2') { + await this.bot.answerCallbackQuery(callbackQuery.id, '❌ Sessão expirada'); + await this.bot.sendMessage(chatId, '❌ Sessão expirada. Por favor, comece novamente.'); + this.userSessions.delete(userId); + return; + } + + await this.bot.answerCallbackQuery(callbackQuery.id); + + if (data === 'fh_vlan_1002') { + // Usar VLAN padrão 1002 + session.vlan = 1002; + + // Limpar sessão + this.userSessions.delete(userId); + + // Executar adição da ONU + await this.executarAdicaoOnuFiberhome(chatId, session); + + } else if (data === 'fh_vlan_custom') { + // Pedir VLAN customizada + session.action = 'adicionar_onu_fiberhome_step3'; + this.userSessions.set(userId, session); + + await this.bot.editMessageText( + `🏷️ **VLAN Customizada**\n\n` + + `Digite o número da VLAN que deseja usar (1-4094):`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); + } + } + /** * Handle callback para confirmar adição de ONU */ diff --git a/src/fiberhome/manager_tl1.js b/src/fiberhome/manager_tl1.js index 44a03c0..ffb7a37 100644 --- a/src/fiberhome/manager_tl1.js +++ b/src/fiberhome/manager_tl1.js @@ -13,6 +13,9 @@ class FiberhomeManager { username: '1', password: '1', timeout: 15000 + }, + olt: { + name: '131.0.192.9' // OLT configurada no TL1 } }; @@ -377,6 +380,177 @@ class FiberhomeManager { } } + /** + * Descobrir porta PON onde a ONU está descoberta + * @param {string} serial - Serial da ONU (MAC address) + */ + async descobrirPortaPON(serial) { + try { + this.logger.debug('Descobrindo porta PON para ONU', { serial }); + + // Conectar ao UNM2000 + const conectado = await this.conectarUNM2000(); + if (!conectado) { + 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++) { + const ponId = `NA-NA-${slot}-${porta}`; + const comando = `LST-UNREGONU::OLTID=${this.config.olt.name},PONID=${ponId}:${this.commandId++}::;`; + + this.logger.debug('Consultando porta PON', { ponId }); + 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())) { + this.logger.info('Porta PON descoberta', { serial, ponId }); + return { + success: true, + portAlias: `${slot}-${porta}`, + slot, + porta + }; + } + } + + // Pequeno delay entre consultas para não sobrecarregar + await new Promise(resolve => setTimeout(resolve, 100)); + } + } + + // ONU não encontrada + this.logger.warn('ONU não encontrada em nenhuma porta PON', { serial }); + return { + success: false, + error: 'ONU não encontrada em nenhuma porta PON. Verifique se a ONU está ligada e descoberta pela OLT.' + }; + + } catch (error) { + this.logger.error('Erro ao descobrir porta PON', { serial, error: error.message }); + return { + success: false, + error: error.message + }; + } + } + + /** + * Adicionar ONU Fiberhome via TL1 + * @param {string} serial - Serial da ONU (MAC address) + * @param {string} usuario - Nome/alias do usuário + * @param {number} vlan - VLAN ID (padrão: 1002) + * @param {string} onuType - Tipo da ONU (AN5506-02-B ou AN5506-01-A) + */ + async adicionarOnuFiberhome(serial, usuario, vlan = 1002, onuType = 'AN5506-02-B') { + try { + this.logger.info('Iniciando adição de ONU Fiberhome via TL1', { + serial, usuario, vlan, onuType + }); + + // Conectar ao UNM2000 + const conectado = await this.conectarUNM2000(); + if (!conectado) { + throw new Error('Não foi possível conectar ao UNM2000'); + } + + // Descobrir porta PON automaticamente + const descoberta = await this.descobrirPortaPON(serial); + if (!descoberta.success) { + throw new Error(descoberta.error); + } + + const portAlias = descoberta.portAlias; + const nameOlt = this.config.olt.name; + + this.logger.info('Porta PON descoberta', { portAlias, nameOlt }); + + // 1. ADD-ONU: Autenticar a ONU + const addOnuCmd = `ADD-ONU::OLTID=${nameOlt},PONID=NA-NA-${portAlias}:${this.commandId++}::AUTHTYPE=MAC,ONUTYPE=${onuType},NAME=${usuario},ONUID=${serial};`; + this.logger.debug('Executando ADD-ONU', { comando: addOnuCmd }); + + const resultadoAdd = await this.executarComandoTL1(addOnuCmd); + if (!resultadoAdd.success) { + throw new Error(`Falha ao adicionar ONU: ${resultadoAdd.error}`); + } + + // Aguardar um pouco para a ONU ser registrada + await new Promise(resolve => setTimeout(resolve, 2000)); + + // 2. SET-WANSERVICE: Configurar WAN services + // Determina quantas portas configurar baseado no tipo da ONU + const numPortas = onuType === 'AN5506-02-B' ? 2 : 1; + + for (let porta = 1; porta <= numPortas; porta++) { + const setWanCmd = `SET-WANSERVICE::OLTID=${nameOlt},PONID=NA-NA-${portAlias},ONUIDTYPE=MAC,ONUID=${serial}:${this.commandId++}::STATUS=1,MODE=2,CONNTYPE=1,VLAN=${vlan},COS=0,QOS=2,UPORT=${porta};`; + this.logger.debug(`Configurando WAN Service porta ${porta}`, { comando: setWanCmd }); + + const resultadoWan = await this.executarComandoTL1(setWanCmd); + if (!resultadoWan.success) { + this.logger.warn(`Aviso ao configurar WAN porta ${porta}: ${resultadoWan.error}`); + // Não lança erro, apenas registra o aviso + } + + // Pequeno delay entre comandos + await new Promise(resolve => setTimeout(resolve, 1000)); + } + + // 3. CFG-WEBADMINISTRATOR: Configurar autenticação web + const cfgWebCmd = `CFG-WEBADMINISTRATOR::OLTID=${nameOlt},PONID=NA-NA-${portAlias},ONUIDTYPE=MAC,ONUID=${serial}:${this.commandId++}::WEBUSERNAME=admin,WEBPASSWORD=clicknet10;`; + this.logger.debug('Configurando autenticação web', { comando: cfgWebCmd }); + + const resultadoWeb = await this.executarComandoTL1(cfgWebCmd); + if (!resultadoWeb.success) { + this.logger.warn(`Aviso ao configurar autenticação web: ${resultadoWeb.error}`); + // Não lança erro, apenas registra o aviso + } + + // Aguardar antes de reiniciar + await new Promise(resolve => setTimeout(resolve, 2000)); + + // 4. RESET-ONU: Reiniciar a ONU + const resetCmd = `RESET-ONU::OLTID=${nameOlt},PONID=NA-NA-${portAlias},ONUIDTYPE=MAC,ONUID=${serial}:${this.commandId++}::;`; + this.logger.debug('Reiniciando ONU', { comando: resetCmd }); + + const resultadoReset = await this.executarComandoTL1(resetCmd); + if (!resultadoReset.success) { + this.logger.warn(`Aviso ao reiniciar ONU: ${resultadoReset.error}`); + // Não lança erro, apenas registra o aviso + } + + this.logger.info('ONU Fiberhome adicionada com sucesso', { + nameOlt, portAlias, serial, usuario, vlan + }); + + return { + success: true, + message: 'ONU adicionada com sucesso', + details: { + olt: nameOlt, + porta: portAlias, + slot: descoberta.slot, + ponPort: descoberta.porta, + serial: serial, + usuario: usuario, + vlan: vlan, + tipo: onuType, + portas: numPortas + } + }; + + } catch (error) { + this.logger.error('Erro ao adicionar ONU Fiberhome', { + serial, error: error.message + }); + return { + success: false, + error: error.message + }; + } + } + /** * Desconectar TL1 */ diff --git a/src/nlp/processor.js b/src/nlp/processor.js index adef546..66b49b4 100644 --- a/src/nlp/processor.js +++ b/src/nlp/processor.js @@ -15,6 +15,7 @@ class NLPProcessor { 'remover_onu': ['remover onu', 'deletar onu', 'apagar onu', 'remove onu', 'delete onu'], 'adicionar_onu': ['adicionar onu', 'add onu', 'criar onu', 'cadastrar onu', 'registrar onu'], 'adicionar_onu_vlan': ['adicionar onu vlan', 'add onu vlan', 'criar onu vlan', 'cadastrar onu vlan'], + 'adicionar_onu_fiberhome': ['adicionar onu fiberhome', 'add onu fiberhome', 'criar onu fiberhome', 'cadastrar onu fiberhome', 'registrar onu fiberhome'], 'ping': ['ping', 'testar', 'test', 'conectividade'], 'admin': ['admin', 'administração', 'administracao', 'painel'], 'usuarios_autorizados': ['usuarios autorizados', 'users autorizados', 'lista usuarios', 'listar usuarios autorizados'], @@ -59,6 +60,9 @@ class NLPProcessor { // Padrões específicos para adicionar ONU com VLAN customizada /^(adicionar|add|criar|cadastrar|registrar)\s+(onu|ont)\s+vlan\s+(\d+)\s+([A-Z0-9]+)$/i, /^(adicionar|add|criar)\s+vlan\s+(\d+)\s+([A-Z0-9]+)$/i, + // Padrões específicos para adicionar ONU Fiberhome via TL1 + /^(adicionar|add|criar|cadastrar|registrar)\s+(onu|ont)\s+fiberhome\s+([A-Z0-9]+)$/i, + /^(fiberhome)\s+(onu|ont)\s+([A-Z0-9]+)$/i, // Padrões específicos para adicionar ONU /^(adicionar|add|criar|cadastrar|registrar)\s+(onu|ont)\s+([A-Z0-9]+)$/i, /^(adicionar|add|criar|cadastrar|registrar)\s+([A-Z0-9]+)$/i, @@ -285,6 +289,29 @@ class NLPProcessor { // Padrões específicos para adicionar ONU if (/adicionar|add|criar|cadastrar|registrar/i.test(action)) { + // Padrão especial: "adicionar onu fiberhome SERIAL" + if (/fiberhome/i.test(fullMatch)) { + let serialNumber; + + // Formato: "adicionar onu fiberhome SERIAL" + if (match.length === 4 && /onu|ont/i.test(fullMatch)) { + serialNumber = match[3]; // Serial + } + // Formato: "fiberhome onu SERIAL" + else if (match.length === 4 && match[1] === 'fiberhome') { + serialNumber = match[3]; // Serial + } + + if (serialNumber) { + return { + action: 'adicionar_onu_fiberhome', + target: serialNumber.trim().toUpperCase(), + confidence: 0.95, + type: 'add_onu_fiberhome_pattern' + }; + } + } + // Padrão especial: "adicionar onu vlan XXX SERIAL" ou "add onu vlan XXX SERIAL" if (/vlan/i.test(fullMatch)) { let vlanId, serialNumber;