Modularizando o src

Dependencies:   EALib EthernetInterface_vz mbed-rtos mbed

Fork of header_main_colinas_V0-20-09-14 by VZTECH

Revision:
106:a34fcf9f0e02
Parent:
105:a930035b6556
Child:
107:cf1e43414adb
--- a/main.cpp	Tue Mar 10 18:10:57 2015 +0000
+++ b/main.cpp	Fri Mar 13 19:40:56 2015 +0000
@@ -4,7 +4,7 @@
 volatile u16_t lpc_low_level_input_counter = 0;
 
 int main()
-{
+{   
     // configura e inicia o wdt 
     init_wdt();
 
@@ -19,10 +19,10 @@
     
     // rotina de verificacao do uso do sistema de memoria
     if( sdram_init() == 1 ) {
-        pc.printf("\r\n******* Failed to initialize SDRAM *******");
+        pc.printf("\r\n******* Failed to initialize SDRAM *******\r\n");
         return 1;
     } else {
-        pc.printf("\r\n******* Success to initialize SDRAM *******");
+        pc.printf("\r\n******* Success to initialize SDRAM *******\r\n");
     }
 
     // inicializa o sistema de arquivo para uso
@@ -32,7 +32,7 @@
     {
         char s[ 32 ];
         mbed_mac_address( s );
-        pc.printf( "\r\n******* ::Mac::%02x:%02x:%02x:%02x:%02x:%02x:: *******", s[0],s[1],s[2],s[3],s[4],s[5] );
+        pc.printf( "\r\n******* ::Mac::%02x:%02x:%02x:%02x:%02x:%02x:: *******\r\n", s[0],s[1],s[2],s[3],s[4],s[5] );
     }
 
     // rotina de inicializacao da interface ETH
@@ -40,7 +40,7 @@
     if( eth_status ) {
         pc.printf("\r\n******* Cannot connect to eth *******\r\n");
     } else {
-        pc.printf("\r\n******* Connection eth - ok *******");
+        pc.printf("\r\n******* Connection eth - ok *******\r\n");
         init_prompt_eth();
         init_external_wdt()
     }
@@ -180,16 +180,16 @@
     
     // desabilita a impressao de caracteres na interface UART3
     //debug_uart3 = false;
+    
+    reset_leds();
 
     /*------------------------------------------ main loop ---------------------------------------------------------------*/
     while( true ) {
-        reset_leds();
-        
         // inicializa o loop afirmando que nao existe comando externo para ser processado pelo prompt.
         udp_query = false;
         from_eth = false;
         
-        // chama rotina de processamento de entrada serial para o prompt
+        // chama rotina de processamento de entrada serial para o prompp
         prompt_process( NULL, 0 );
         
         //begin verificacao e tratamento dos pacotes recebidos via UDP-ETH 
@@ -269,7 +269,7 @@
                             bool question_alive = ( wake_msg[ 5 ] == '?' );
                             if( wake_msg[ 5 ] == '*' ) wdt.kick();
                             
-                            snprintf( wake_msg, 48,"wdt:%u,%u,%u,%c,%u,%u,%u,%u,%u:", 
+                            snprintf( wake_msg, 48,"wdt:%u,%u,%u,%c,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u,%u:", 
                                 uptime, 
                                 invite_counter, 
                                 external_wdt, 
@@ -278,8 +278,31 @@
                                 v_cb->size(),
                                 ts->remain_timeslices(), 
                                 sip_socket_send_failure, 
-                                v_call->size()
+                                v_call->size(),
+                                pkg_cksok,
+                                pkg_ckserr,
+                                pkg_zero,
+                                out_of_range,
+                                missed_pkg,
+                                delayed_pkg_to_cb,
+                                cpld_pkg_tx_counter,
+                                cpld_pkg_rx_counter,
+                                eth_wdt,
+                                pkg_wdt,
+                                miss_fw_send_pkg,
+                                miss_prompt_udp_send_pkg,
+                                miss_sip_registry_send_pkg,
+                                miss_sip_invite_send_pkg,
+                                miss_sip_bye_send_pkg,
+                                miss_sip_unregistry_send_pkg,
+                                miss_sip_ok_send_pkg,
+                                miss_sip_rcv_bye_send_pkg,
+                                miss_wdt_send_pkg,
+                                miss_prompt_udp_send_pkg,
+                                miss_ftp_udp_send_pkg,
+                                miss_prompt_udp_rcv_pkg                                
                             );
+            
                             wake_msg[ 768 - 1 ] = 0;
                             int send = udp_wdt_client.sendTo( udp_wdt_server, wake_msg, strlen( wake_msg ) );
                             if( send != strlen( wake_msg ) )
@@ -311,6 +334,8 @@
         
         // atualiza o valor do contador max_registered_cbx
         if( v_cb->size() > max_registered_cbx ) max_registered_cbx = v_cb->size();
+        
+         
 
         // executa a cada 5 segundos comandos e verificacoes ( principalmente debugs )
         if( sync_timer.read() > 5 ) {
@@ -356,6 +381,8 @@
                 if( debug_wake == true ) send_msg( "Time to wake" );
             }
         }
+        
+         
 
         // zera os contadores de pacotes recebidos na interface CBx->Header
         if( r_stats ) {
@@ -373,6 +400,8 @@
             r_stats = false;
             stats = true;
         }
+        
+         
 
         // exibe o valor dos contadores de pacotes recebidos na interfacao CBx->ETH
         if( stats ) {
@@ -382,9 +411,12 @@
             send_msg( str );
             stats =false;
         }
+        
+         
 
         // exibe uma lista ( em ordem crescente e por ramais ) dos cbx que ja se registraram ao menos uma vez
-        if( list ) {
+        if( list ) 
+        {
             uint8_t missed_cb = ( ( max_ext - min_ext ) + 1 ) - v_cb->size();
 
             if( ( max_ext % 2 ) == 0 ) missed_cb++;
@@ -419,14 +451,131 @@
             }
             list = false;
         }
+        
+         
+        
+        // validar na proxima iteracao.
+        if( long_list ) 
+        {
+            uint8_t missed_cb = ( ( max_ext - min_ext ) + 1 ) - v_cb->size();
 
-        //TODO implementar um showcb ordenado crescentemente por ext e com o timeout pra cada tupla
-        if( long_list ) {
+            if( ( max_ext % 2 ) == 0 ) missed_cb++;
+
+            if( min_ext % 2 ) missed_cb++;
+
+            if( min_ext == 0 && max_ext == 0 ) missed_cb = 0;
+
+            {
+                int ext_list[ __MAX_CB_IN_A_BRANCH__ ];
+                
+                if( v_cb->size() >= 1 ) {
+                    for( register int i = 0; i < v_cb->size(); i++ )
+                    {
+                        ext_list[ i ] = ( ( Call_Box * )v_cb->get_element( i ) )->get_ext();
+                    }
+                    qsort( ext_list, v_cb->size(), sizeof( int ), ls_comp );
+                }   
+                
+                send_msg("Registered %d[ %d ] CBx ( %d - %d ) - Missed %d -- Remain_timeslices :: %d :: v_call->size() :: %d", v_cb->size(), max_registered_cbx, min_ext, max_ext, missed_cb, ts->remain_timeslices(), v_call->size() );
+                
+                for( register uint8_t i = 0; i < v_cb->size(); i++ ) {
+                    
+                    Call_Box * cb = __find_CB__( v_cb, ext_list[ i ] );
+            
+                    if( cb != NULL )
+                    {
+                        char cb_status[ 32 ];
+                        char cb_sip_status[ 32 ];
+                        switch( cb->status ) {
+                            case cb_idle : {
+                                strcpy( cb_status, "cb_idle" );
+                                break;
+                            }
+                            case cb_ringing : {
+                                strcpy( cb_status, "cb_ringing" );
+                                break;
+                            }
+                            case cb_trying : {
+                                strcpy( cb_status,"cb_trying" );
+                                break;
+                            }
+                            case cb_on_call : {
+                                strcpy( cb_status, "cb_on_call" );
+                                break;
+                            }
+                            case cb_busy : {
+                                strcpy( cb_status, "cb_busy" );
+                                break;
+                            }
+                            case cb_denied : {
+                                strcpy( cb_status, "cb_denied" );
+                                break;
+                            }
+                        }
+                        switch( cb->sip->status ) {
+                            case sip_idle : {
+                                strcpy( cb_sip_status, "sip_idle" );
+                                break;
+                            }
+                            case sip_waiting_trying : {
+                                strcpy( cb_sip_status, "sip_waiting_trying" );
+                                break;
+                            }
+                            case sip_trying : {
+                                strcpy( cb_sip_status, "sip_trying" );
+                                break;
+                            }
+                            case sip_ringing : {
+                                strcpy( cb_sip_status, "sip_ringing" );
+                                break;
+                            }
+                            case sip_busy : {
+                                strcpy( cb_sip_status, "sip_busy" );
+                                break;
+                            }
+                            case sip_ok : {
+                                strcpy( cb_sip_status, "sip_ok" );
+                                break;
+                            }
+                            case sip_on_call : {
+                                strcpy( cb_sip_status, "sip_on_call" );
+                                break;
+                            }
+                            case sip_denied : {
+                                strcpy( cb_sip_status, "sip_denied" );
+                                break;
+                            }
+                        }
+                        char cbx_to_string[ 254 ];
+                        char aux[ 16 ];
+                        strcpy( cbx_to_string, "Ext :: " );
+                        itoa( cb->get_ext(), aux , 10 );
+                        strcat( cbx_to_string, aux );
+                        strcat( cbx_to_string, " :: Port :: " );
+                        itoa( cb->get_port(), aux , 10 );
+                        strcat( cbx_to_string, aux );
+                        strcat( cbx_to_string, " :: Status -- " );
+                        strcat( cbx_to_string, cb_status );
+                        strcat( cbx_to_string, " - " );
+                        strcat( cbx_to_string, cb_sip_status );
+                        if( cb->get_timeslice() != 0 ) {
+                            strcat( cbx_to_string, " -- on TimeSlice :: " );
+                            itoa( cb->get_timeslice(), aux , 10 );
+                            strcat( cbx_to_string, aux );
+                        }
+                        send_msg( cbx_to_string );
+                    }
+                }   
+                
+            }
             long_list = false;
         }
+        
+         
 
         // exibe uma lista de cbx por ordem de registro contendo status do cbx e do sip vinculado nesse cbx
-        if( pshowcb == true ) {
+        if( pshowcb == true ) 
+        {            
             send_msg("Registered %d ( of %d ) CBx ( %d - %d ) -- Remain_timeslices :: %d :: v_call->size() :: %d", v_cb->size(), max_registered_cbx, min_ext, max_ext, ts->remain_timeslices(), v_call->size() );
             for( register uint8_t i = 0; i < v_cb->size(); i++ ) {
                 Call_Box * cb = ( Call_Box * )v_cb->get_element( i );
@@ -524,15 +673,21 @@
                 send_msg("ext :: %d -- port :: %d -- timer %d", cb->get_sip_ext(), cb->get_sip_port(), cb->get_timer() );
             }
         } 
+        
+         
 
         // aciona rotina de envio de pacote de flood
         if( pflood == true ) flood();
+        
+         
 
         // exibe status de conexao ETH
         if( debug_eth ) {
             debug_eth = false;
             send_msg("Eth status %s", ( eth_status == 0 ) ? "Connected" : "Disconnected" );
         }
+        
+         
 
         // testa se existe um pacote recebido pela interface CBx->Header pendente para ser processado.
         if( status != __WAITING__ ) {
@@ -666,12 +821,16 @@
             } else type = __DO_NOTHING__;
         }
         
+         
+        
         // exibe uptime atual
         if( show_uptime )
         {
             show_uptime = false;
             send_msg("Uptime: %d", uptime );
         }
+        
+         
 
         // exibe algumas informacoes pertinentes sobre quantidade de variaveis alocadas e tamanho de alguns objetos.
         if( sizes == true ) {
@@ -694,6 +853,8 @@
             send_msg("Sizeof Timeslice :: %u", sizeof( Timeslice ) );
             send_msg("Sizeof Watchdog :: %u", sizeof( Watchdog ) );
         }
+        
+         
 
         // zera os contadores de cks de pacotes recebidos na interface CBx->Header, e outros contadores relacionados
         if( reset_cks == true ) {
@@ -708,6 +869,8 @@
             cpld_pkg_rx_counter = 0;
             pcks_s = true;
         }
+        
+         
 
         // exibe os contadores de cks de pacotes recebidos na interface CBx->Header, e outros contadores relacionados
         if( pcks_s == true ) {
@@ -733,6 +896,8 @@
             pcks_s = false;
         }
         
+         
+        
         // zera os contadores de pacotes que resultaram em falha de envio vio ETH
         if( reset_missed_send_udp_pkg ){        
             miss_fw_send_pkg = 0;                                                                                                                 
@@ -751,6 +916,8 @@
             missed_send_udp_pkg = true;
         }
         
+         
+        
         // exibe estatisticas de pacotes que resultaram em falha de envio na interface ETH
         if( missed_send_udp_pkg )
         {
@@ -784,6 +951,7 @@
             missed_send_udp_pkg = false;
         }
         
+         
         // rotina de teste para sobrecarga do processamento do cbx.
         if( flood_bug_pkg ){
             static int id = 0x10;
@@ -792,6 +960,7 @@
                 ( char * )buffer, id++, CB_BUFFER_SIZE - __VZ_HEADER_OFFSET__, write_buffer ) );    
         }
         
+         
         // toggle nos leds de debug da header.
         if( led_sync_timer.read() >= 1 ) {
             led_sync_timer.reset();
@@ -799,19 +968,23 @@
             CAB_LED = !CAB_LED;
         }
         
+         
         // rotina de teste ( usados durante desenvolvimento
+        /*
         if( main_test )
         {
-            static int next_ext = 1314;
-            static int next_port = 1923;
+            static int n = 0;
+            static int next_ext = 5000;
             
             main_test = false;
             data = buffer;
-            ext = next_ext++;
-            port = next_port++;
-            type = __INVITE__;
+            ext = next_ext + ( n * ( ( n % 2 ) ? 1 : -1 ) );
+            n++;
+            port = ext;
+            type = __REGISTRY__;
         }
-        
+        */
+         
         // begin switch para tratemento de pacote baseado no type
         switch( type ) {
             case __DO_NOTHING__ :
@@ -1183,7 +1356,6 @@
             break;
         }//end switch para tratemento de pacote baseado no type
         
-        
         { // rajada
             /***
                 [ Principio ]
@@ -1199,8 +1371,10 @@
 
                 // procura por CBx em ligaçao sequencialmente
                 register int i = 0;
+                
                 for( ; i < v_cb->size(); i++ ) {
                     Call_Box * cb = (Call_Box * )v_cb->get_element( i );
+                    debug_msg("--%p--", cb );
                     if( ( cb->status == cb_ringing ) || ( cb->status == cb_trying ) || ( cb->status == cb_on_call ) ) {
                         if( i > retry_invite_pkg ) {
                             retry_invite_pkg = i;
@@ -1251,7 +1425,9 @@
                 }
             }
         }
-
+        
+        //
+        
         /***
             [ Principio ]
                 -- Para cada CBx em ligaçao
@@ -1266,14 +1442,15 @@
                             - Caso nao seja encontrado
                                 - Exibe msg de erro condicionado a debug
         ***/
+        
         for( register uint8_t i = 0; i < v_call->size(); i++ ) {
+            //debug_msg("");
             VZ_call * call = ( VZ_call * )v_call->get_element( i );
             int length = 0;
             char * tmp = call->get_eth_message( &length );
             if( tmp != NULL ) {
                 int cb_port = 0xffff;
                 Call_Box * cb = __find_CB__( v_cb, call->get_cb_ext() );
-
                 if( cb != NULL ) {
                     cb_port = cb->get_port();
 
@@ -1285,7 +1462,7 @@
                 } else if( debug_main ) debug_msg("received missed package  from CBx :: %i -- Type :: %i", ext, type );
             }
         }
-
+        //
         /***
             [ Principio ]
                 -- Verificar se já se passou determinada unidade de tempo
@@ -1293,21 +1470,25 @@
                 [ 1 ] -- Encaminha periodicamente um pacote de __REGISTRY__ para cada CBx, um por vez.
                 [ 2 ] -- Busca por elementos que constem sem seus pares registrados e manda um __PROMPT__ ping para cada um, um por vez.
         ***/
-        
-        if( timer_sync_refresh.read_ms() > 250 ) {
+
+        if( timer_sync_refresh.read_ms() > 250 )
+        {
             timer_sync_refresh.reset();
 
             static uint8_t mode = TIME_TO_REFRESH;
             
-            if( mode == TIME_TO_REFRESH ) {
+            if( mode == TIME_TO_REFRESH )
+            {
                 mode = TIME_TO_WAKE_UP;
-                refresh( v_cb, buffer, write_buffer, NULL );
-            } else {
+                refresh( v_cb );
+            }
+                else
+            {
                 mode = TIME_TO_REFRESH;
-                if( wake_all ) if( v_call->size() == 0 ) wake_all_up( v_cb, buffer, write_buffer );       
+                if( wake_all ) if( v_call->size() == 0 ) wake_all_up( v_cb );
             }
         }
-
+        
         // check sip messages only for cbx in call ?
         int ext_to__be_removed = sip_manager( v_cb );
         if( ext_to__be_removed > 0x00 ) {
@@ -1342,9 +1523,11 @@
         /* Verifica andamento de ligações para eventualmente encerra-las por timeout */
         call_manager( v_call, v_cb, buffer, write_buffer, ts );
 
+        
         /* tratamento de pedidos de ligação já em andamento com o * */
         invite_handler( v_call, v_cb, ts, NULL );
 
+        
         /* rotina de verificação de TS's perdidos */
         if( ( v_call->size() == 0 ) && ( ts->remain_timeslices() != __MAX_TIMESLICES__ ) ) {
             bool ts_reset = true;
@@ -1361,18 +1544,24 @@
             }
         }
 
+        
         /* rotina que esvazia possiveis pacotes que não foram transmitidos para evitar conflito */
         tx_buffer_ring_buffer_handler();
 
+        
         // atribui o valor default para a variavel type
         type = __DO_NOTHING__;
 
+        
         // verifica o status da conexao ETH, caso exteja conectado ( == 0 ) atribui o valor maximo ao contador de controle
         if( eth_status == 0 ) eth_wdt = ETH_CONNECT_TIMEOUT;
-
+        
+        
+        
         // responsavel por atualizar os contadores de controle utilizados para tickar o wdt
         // e tickar o wdt
         if( wdt_timer.read() >= 1 ) {
+            
             //FIXME remove myself
             uptime++;
 
@@ -1389,6 +1578,7 @@
             }
         }
         
+        
         // exibe informacoes referentes ao wdt, ultimo reset, status da eth, tempo em segundos desde o ultimo tick dowdt externo, 
         // tempo em segundos desde o ultimo pacote recebido da interface fibra
         if( debug_wdt ) {