Modularizando o src

Dependencies:   EALib EthernetInterface_vz mbed-rtos mbed

Fork of header_main_colinas_V0-20-09-14 by VZTECH

main_app_functions.cpp

Committer:
klauss
Date:
2015-07-20
Revision:
130:850163037da5
Parent:
129:d73538fbc017
Child:
131:938ab88facae

File content as of revision 130:850163037da5:

#include "main_app_functions.h"

inline void reset_leds() { led1 = led2 = 1; led3 = led4 = 0; }

int header_app_init ( void )
{
 
    send_msg ( "" );
 
    if ( debug_app_init ) send_msg ( "init_wdt() :: %s", ( init_wdt () == 0 ) ? "Ok" : "Failure" );
    
    if ( debug_app_init ) send_msg ( "config_lpc() :: %s", ( config_lpc () == 0 ) ? "Ok" : "Failure" );
    
    if ( debug_app_init ) send_msg ( "start_cpld() :: %s", ( start_cpld () == 0 ) ? "Ok" : "Failure" );
    
    if( sdram_init() == 1 ) {
        send_msg("******* Failed to initialize SDRAM *******");
        return 1;
    } else {
        send_msg("******* Success to initialize SDRAM *******");
    }
    
    int init_fsystem_ret = init_fsystem();
    if( init_fsystem_ret & BIT0 )
    {
        send_msg("******* File system configured!!*******");
    }
    
    if( init_fsystem_ret & BIT1 )
    {
        send_msg("******* File System Ready *******");
    }
    
    {
        char s[ 32 ];
        mbed_mac_address( s );
        send_msg( "::Mac::%02x:%02x:%02x:%02x:%02x:%02x:: ", s[0],s[1],s[2],s[3],s[4],s[5] );
    }
    
    eth_status = __init_eth__ ();
    if ( eth_status )
    {
        send_msg("******* Cannot connect to eth *******");
    } else {
        send_msg("******* Connection eth - ok *******");
        int init_prompt_eth_ret = init_prompt_eth();
        
        if ( init_prompt_eth_ret == BIT0 ) send_msg("******* Prompt eth UDP Ready *******");
        
        if ( init_prompt_eth_ret == BIT1 ) send_msg("******* Prompt eth TCP Ready *******");
        
        if ( debug_app_init ) send_msg ( "init_prompt_eth() :: %s", ( init_prompt_eth_ret == ( BIT0 bitor BIT1 ) ) ? "Ok" : "Failure" );
        
        if ( debug_app_init ) send_msg ( "init_external_wdt() :: %s", ( init_external_wdt () == 0 ) ? "Ok" : "Failure" );
        
        if ( debug_app_init ) send_msg ( "init_bl() :: %s", ( init_bl() == 0 ) ? "Ok" : "Failure" );
        
        if ( debug_app_init ) send_msg ( "init_clock () :: %s", ( init_clock () == 0 ) ? "Ok" : "Failure" );
        
        if ( debug_app_init ) send_msg ( "init_pwr_src () :: %s", ( init_pwr_src () == 0 ) ? "Ok" : "Failure" );
    }
    
    sync_timer.start();
    
    led_sync_timer.start();
    
    ext = 0;

    port = 0;
    
    buffer_from_cb_ptr = ( uint8_t * )RXBuffer;
    
    data = NULL;
    
    type = DO_NOTHING;
    
    v_cb = new Vector();
    if( v_cb == NULL ) {
        while( v_cb == NULL ) {
            Vector * v_cb = new Vector();
            if( sync_timer.read() > 5 ) {
                if( debug_memory ) send_msg("Call_Box vector allocation fail");
                sync_timer.reset();
            }
        }
    }
    
    if ( debug_app_init ) send_msg ( "v_cb :: %s", ( v_cb not_eq NULL ) ? "Ok" : "Failure" );
    
    v_call = new Vector();
    if( v_call == NULL ) {
        while( v_call == NULL ) {
            Vector * v_call = new Vector();
            if( sync_timer.read() > 5 ) {
                if( debug_memory ) send_msg("Call vector allocation fail");
                sync_timer.reset();
            }
        }
    }
    
    if ( debug_app_init ) send_msg ( "v_call :: %s", ( v_call not_eq NULL ) ? "Ok" : "Failure" );
    
    ts = new Timeslice();
    if( ts == NULL ) {
        memory_is_over = true;
        if( debug_memory ) send_msg("TS allocation fail");
    }
    
    if ( debug_app_init ) send_msg ( "TS :: %s", ( ts not_eq NULL ) ? "Ok" : "Failure" );
    
    for( register uint16_t i = 0; i < CB_BUFFER_SIZE; i++ ) {
        cb_rx_buffer[ i ] = 0;
        cb_tx_buffer[ i ] = 0;
    }
    
    reset_leds();
    
    udp_timer.start();
    
    if ( debug_app_init ) send_msg ( "init_fw_handler() :: %s", ( init_fw_handler() == 0 ) ? "Ok" : "Failure" );
    
    if ( debug_app_init ) send_msg ( "init_ranges() :: %s", ( init_ranges() == 0 ) ? "Ok" : "Failure" );
    
    if ( debug_app_init ) send_msg ( "init_refresh() :: %s", ( init_refresh() == 0 ) ? "Ok" : "Failure" );
    
    if ( debug_app_init ) send_msg ( "init_sync_refresh() :: %s", ( init_sync_refresh() == 0 ) ? "Ok" : "Failure" );
    
    count = 0;
    
    max_registered_cbx = 0;
    
    wake_all = false;
    
    pkg_wdt = RX_CB_IDLE;
    
    eth_wdt = ETH_CONNECT_TIMEOUT;
    
    invite_retry_timer.start();
    
    if ( debug_app_init ) send_msg ( "hex_init() :: %s", ( hex_init() == 0 ) ? "Ok" : "Failure" );
    
    reset_leds();
    
    lpc_low_level_input_counter = 0;
    
    if ( debug_app_init ) send_msg ( "init_hello () :: %s", ( init_hello ()  == 0 ) ? "Ok" : "Failure" );
    
    test_ts_timer.start ();
    
    pwr_src_timer.start ();
    
    send_msg ( "" );
    
    return ( 0 );   
}


int try_reconnect_with_eth ( void )
{
    eth_status = __init_eth__();
    
    if ( eth_status )
    {
        send_msg("******* Cannot connect to eth *******");
    } else {
        send_msg("******* Connection eth - ok *******");
        int init_prompt_eth_ret = init_prompt_eth();
        
        if ( init_prompt_eth_ret == BIT0 ) send_msg("******* Prompt eth UDP Ready *******");
        
        if ( init_prompt_eth_ret == BIT1 ) send_msg("******* Prompt eth TCP Ready *******");
        
        if ( debug_app_init ) send_msg ( "init_prompt_eth() :: %s", ( init_prompt_eth_ret == ( BIT0 bitor BIT1 ) ) ? "Ok" : "Failure" );
        
        if ( debug_app_init ) send_msg ( "init_external_wdt() :: %s", ( init_external_wdt() == 0 ) ? "Ok" : "Failure" );
        
        if ( debug_app_init ) send_msg ( "init_bl() :: %s", ( init_bl() == 0 ) ? "Ok" : "Failure" );
        
        if ( debug_app_init ) send_msg ( "init_clock() :: %s", ( init_clock() == 0 ) ? "Ok" : "Failure" );
        
        if ( debug_app_init ) send_msg ( "init_pwr_src () :: %s", ( init_pwr_src () == 0 ) ? "Ok" : "Failure" );
    }
    
    return eth_status;
}


int show_stats ( void )
{
    char str[ 200 ];
    int snprintf_ret = snprintf( str, 200, ""
            "\n\rReceived Pkgs::\n\r "
            "Boot :: %u\n\r "
            "Registry :: %u\n\r "
            "Invite :: %u\n\r "
            "Audio :: %u\n\r "
            "Telemetry :: %u\n\r "
            "CB_stats :: %u\n\r "
            "CB_bye :: %u\n\r "
            "Prompt :: %u\n\r "
            "Flood :: %u\n\r "
            "Bootloader_cbx :: %u\n\r",
            boot_counter, 
            registry_counter, 
            invite_counter,
            audio_counter, 
            telemetry_counter, 
            cb_stats_counter, 
            cb_bye_counter, 
            prompt_counter, 
            flood_counter,
            bootloader_cbx_counter
    );
    send_msg( str );
    
    if ( debug_string_length ) debug_msg("str.length ( %d )", snprintf_ret );
    return ( snprintf_ret );
}


int reset_stats ( void )
{
    boot_counter = 0;
    registry_counter = 0;
    invite_counter = 0;
    audio_counter = 0;
    telemetry_counter = 0;
    cb_bye_counter = 0;
    prompt_counter = 0;
    flood_counter = 0;
    bootloader_cbx_counter = 0;
    cb_stats_counter = 0;
    fw_counter = 0; 

    return ( 0 );
}

int show_cb_list ( Vector * v_cb )
{
    uint8_t missed_cb = ( ( max_ext - min_ext ) + 1 ) - v_cb->size();

    if( ( max_ext % 2 ) == 0 ) missed_cb++;

    if( min_ext % 2 ) missed_cb++;

    if( min_ext == 0 && max_ext == 0 ) missed_cb = 0;

    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() );
    if( v_cb->size() == 1 ) {
        send_msg(" %d ", ( ( Call_Box * )v_cb->get_element( 0 ) )->get_ext() );
    } else if( v_cb->size() > 1 ) {
        char str[ 1024 ];
        int ext_list[ MAX_CB_IN_A_BRANCH ];
        register int i = 0;
        for( ; 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 );

        char aux[ 16 ];
        strcpy( str, "\r\n> " );
        for( i = 0; i < v_cb->size() - 1; i++ ) {
            sprintf( aux, "%i, ", ext_list[ i ] );
            strcat( str, aux );
            if( ( i not_eq 0 ) and not( ( i + 1 ) % 16 ) ) strcat( str, "\r\n> " );
        }
        sprintf( aux, "%i ", ext_list[ i ] );
        strcat( str, aux );
        send_msg( "%s", str );
    }
    
    return ( 0 );
}

int show_cb_long_list ( Vector * v_cb, bool show_time )
{
    uint8_t missed_cb = ( ( max_ext - min_ext ) + 1 ) - v_cb->size();

    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 not_eq NULL )
            {
                char cb_status[ 32 ];
                char cb_sip_status[ 32 ];
                switch ( cb -> get_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;
                    }
                    case cb_bootloader : {               
                        strcpy( cb_status, "cb_bootloader" );
                        break;
                    }
                }
                
                switch( cb -> get_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 ];
                snprintf ( cbx_to_string, sizeof ( cbx_to_string ), 
                    "Ext :: %5i :: Port :: %5i :: Status -- %s - %s",
                    cb->get_ext(), cb->get_port(), cb_status, cb_sip_status
                );
                
                if( cb->get_timeslice() not_eq 0 )
                {
                    char aux[ 32 ];
                    snprintf ( aux, sizeof ( aux ), " -- on TimeSlice :: %i",  cb->get_timeslice() );
                    strcat( cbx_to_string, aux );
                }
                
                if ( show_time )
                {
                    char get_timer_msg [ 128 ];
                    
                    snprintf ( get_timer_msg, sizeof ( get_timer_msg ) -1, " -- timer %4i [ %s ",
                        cb -> get_timer (), 
                        ( cb -> get_overflow_flag () ) ? "Overflow" : "Ok"
                    );
                
                    int get_overflow_times_tmp = cb -> get_overflow_times ();
                
                    if ( get_overflow_times_tmp == 0 ) strcat ( get_timer_msg, "]" );
                
                    else {
                        char strcat_tmp [ 16 ];
                        if ( get_overflow_times_tmp == 1 ) snprintf( strcat_tmp, sizeof ( strcat_tmp ) - 1, "1 time ]" );
                        
                        else snprintf( strcat_tmp, sizeof ( strcat_tmp ) - 1, "%u times ]", get_overflow_times_tmp );
                        
                        strcat ( get_timer_msg, strcat_tmp );
                    }
                    
                    strcat ( cbx_to_string, get_timer_msg );
                }
                
                send_msg( cbx_to_string );
            }
        }   
    }
    
    return ( 0 );
}

int show_cb ( Vector * v_cb )
{
    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 );
        char cb_status[ 32 ];
        char cb_sip_status[ 32 ];
        switch ( cb -> get_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;
            }
            case cb_bootloader : {               
                strcpy( cb_status, "cb_bootloader" );
                break;
            }
        }
        switch( cb -> get_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 ];
        snprintf ( cbx_to_string, sizeof ( cbx_to_string ), 
            "Ext :: %5i :: Port :: %5i :: Status -- %s - %s",
            cb->get_ext(), cb->get_port(), cb_status, cb_sip_status
        );
        
        if( cb->get_timeslice() not_eq 0 )
        {
            char aux[ 32 ];
            snprintf ( aux, sizeof ( aux ), " -- on TimeSlice :: %i",  cb->get_timeslice() );
            strcat( cbx_to_string, aux );
        }
        
        
        send_msg( cbx_to_string );
    }
    
    return ( 0 );
}

int show_cb_sip ( Vector * v_cb )
{
    send_msg(":: Sip :: %u", v_cb -> size () );
    for ( register uint8_t i = 0; i < v_cb -> size (); i++ )
    {
        Call_Box * cb = ( Call_Box * ) v_cb -> get_element ( i );
        
        char tmp_send_msg [ 256 ];
        
        snprintf ( tmp_send_msg, sizeof ( tmp_send_msg ) - 1, 
            "ext :: %5i -- port :: %5i -- timer %4i [ %s ", 
            cb -> get_sip_ext (), 
            cb -> get_sip_port (), 
            cb -> get_timer (), 
            ( cb -> get_overflow_flag () ) ? "Overflow" : "Ok"
        );
        
        int get_overflow_times_tmp = cb -> get_overflow_times ();
        
        if ( get_overflow_times_tmp == 0 ) strcat ( tmp_send_msg, "]" );
        
        else {
            char strcat_tmp [ 16 ];
            if ( get_overflow_times_tmp == 1 ) snprintf( strcat_tmp, sizeof ( strcat_tmp ) - 1, "1 time ]" );
            
            else snprintf( strcat_tmp, sizeof ( strcat_tmp ) - 1, "%d times ]", get_overflow_times_tmp );
            
            strcat ( tmp_send_msg, strcat_tmp );
        }
        
        send_msg ( tmp_send_msg );
    }    
    
    return ( 0 );
}

int show_sizes ( void )
{
    sizes = false;
    send_msg("CB_New (%u) -- CB_Delete (%u)", cb_new_counter, cb_delete_counter );
    send_msg("SIP_New (%u) -- SIP_Delete (%u)", sip_new_counter, sip_delete_counter );
    send_msg("RTP_header_New (%u) -- RTP_header_Delete (%u)", rtp_header_new_counter, rtp_header_delete_counter );
    send_msg("RTP_body_New (%u) -- RTP_body_Delete (%u)", rtp_body_new_counter, rtp_body_delete_counter );
    send_msg("Call_New (%u) -- Call_Delete (%u)", call_new_counter, call_delete_counter );
    send_msg("lpc_low_level_input_counter :: %d", lpc_low_level_input_counter );
    send_msg("Memory is %s", ( memory_is_over ) ? "Over" : "Ok" );
    send_msg("Missed_Pkg :: %d ::", missed_pkg );
    send_msg("Sizeof Sip :: %u", sizeof( Sip ) );
    send_msg("Sizeof Call_Box :: %u", sizeof ( Call_Box ) );
    send_msg("Sizeof VZ_call :: %u", sizeof( VZ_call ) );
    send_msg("Sizeof RTP :: %u", sizeof( RTP ) );
    send_msg("Sizeof RTP_Header :: %u", sizeof( RTP_Header ) );
    send_msg("Sizeof RTP_Body :: %u", sizeof( RTP_Body ) );
    send_msg("Sizeof Vector :: %u", sizeof( Vector ) );
    send_msg("Sizeof Timeslice :: %u", sizeof( Timeslice ) );
    send_msg("Sizeof Watchdog :: %u", sizeof( Watchdog ) );
    
    return ( 0 );
}

int check_udp_packages_pending ( Vector * v_cb )
{
    fd_set fdSet;
    FD_ZERO(&fdSet);

    for( register uint8_t i = 0; i < v_cb->size(); i++ ) {
        Call_Box * cb = (Call_Box *)v_cb->get_element( i );
        FD_SET( cb->get_sip_socket_fd(), &fdSet);
    }
    
    /* Recepcao de pacotes UDP para atualizacao de callboxes */
    FD_SET( udp_bl_client.get_fd (), &fdSet);
    
    /* Recepcao de pacotes UDP para "tickagem" do watchdog */
    FD_SET( udp_wdt_client.get_fd (), &fdSet);
    
    // adiciona o socket de comandos prompt-UDP-ETH
    FD_SET( udp_client.get_fd (), &fdSet );
    
    // adiciona o socket de pedido de clock para o servidor
    FD_SET( clock_sock.get_fd (), &fdSet );
    
    struct timeval t;
    t.tv_sec = 0;
    t.tv_usec = 0;
    int ret = lwip_select ( FD_SETSIZE, &fdSet, NULL, NULL, &t );
    
    if ( ( udp_bl_timer.read() > 30) and (bl_start_flag) ) 
    {
        udp_bl_timer.stop();
        udp_bl_timer.reset();
        bl_start_flag = 0;
        if (bl_ts not_eq 0) {
            ts->return_timeslice( bl_ts );
            bl_ts = 0;
        }
        if (bl_cb not_eq NULL) {
            bl_cb -> set_timeslice( 0 );
            bl_cb -> cb_set_status ( cb_idle );
            bl_cb = NULL;
        }
    }

    if ( ret > 0 )
    {  
        for( register uint8_t i = 0; i < v_cb->size(); i++ ) {
            Call_Box * cb = (Call_Box *)v_cb->get_element( i );
            int fd =  cb->get_sip_socket_fd();
            if( FD_ISSET( fd, &fdSet ) ) {
                int rcv = cb->sip_udp_incomming_pkg();
            }
        }
        
        /* Tratamento dos pacotes de bootloader vindo do servidor */
        if( FD_ISSET( udp_bl_client.get_fd(), &fdSet ) ) {
            if( udp_bl_client.receiveFrom( udp_bl_server, bl_recv_buffer, sizeof( bl_recv_buffer ) ) > 0 ) {
                uint16_t cnt = 0;
                if (debug_bootloader) {
                    pc.printf("\r\nPACOTE SRV->HDR {");
                    for (cnt = 0;cnt < UDP_BL_SIZE;cnt++) {
                        if ((cnt % 30) == 0) {
                            pc.printf("\r\n  ");
                            pc.printf(hex16(cnt));
                            pc.printf(" : ");
                        }
                        pc.printf(hex8(bl_recv_buffer[cnt]));
                        pc.printf(", ");
                    }
                    pc.printf("\r\n}");
                }
                bl_peer = ((uint8_t)bl_recv_buffer[0])*256 + (uint8_t)bl_recv_buffer[1];
                bl_send_buffer[0] = bl_recv_buffer[0];
                bl_send_buffer[1] = bl_recv_buffer[1];
                for (cnt = 2;cnt < UDP_BL_SIZE;cnt++) {
                    bl_send_buffer[cnt] = 0;
                }
                
                if ((bl_ts == 0) and !(bl_start_flag)) {
                    bl_ts = ts->get_timeslice();
                }
                
                /* caso nao haja timeslice disponivel informar servidor */
                if ((bl_ts == 0) and !(bl_start_flag)) {
                    strncpy(bl_send_buffer + 2,"cbxdead\x00",8);
                    int udp_bl_client_ret = udp_bl_client.sendTo( udp_bl_server, bl_send_buffer, strlen( bl_send_buffer ) );
                    
                    if ( udp_bl_client_ret not_eq strlen( bl_send_buffer ) )
                    {
                            // TODO implementar os reconnects do bl
                    }
                } else {
                    
                    /* pacote para verificar se o callbox esta disponivel */
                    if (!(strncmp(bl_recv_buffer + 2,"avaiable?",9))) {
                        bl_start_flag = 1;
                        udp_bl_timer.start();
                        udp_bl_timer.reset();
                        strncpy(bl_send_buffer + 2,"cbxalive\x00",9);
                        if (debug_bootloader) {
                            pc.printf("\r\nPACOTE HDR->SRV {");
                            for (cnt = 0;cnt < UDP_BL_SIZE;cnt++) {
                                if ((cnt % 30) == 0) {
                                    pc.printf("\r\n  ");
                                    pc.printf(hex16(cnt));
                                    pc.printf(" : ");
                                }
                                pc.printf(hex8(bl_send_buffer[cnt]));
                                pc.printf(", ");
                            }
                            pc.printf("\r\n}");
                        }
                        udp_bl_client.sendTo( udp_bl_server, bl_send_buffer, strlen( bl_send_buffer ) );
                    }
                    
                    /* pacote para indicar o termino do processo de atualizacao */
                    else if (!(strncmp(bl_recv_buffer + 2,"finished",8))) {
                        bl_start_flag = 0;
                        if (bl_ts not_eq 0) {
                            ts->return_timeslice( bl_ts );
                            bl_ts = 0;
                        }
                        if (bl_cb not_eq NULL) {
                            bl_cb->set_timeslice( 0 );
                            bl_cb -> cb_set_status( cb_idle );
                            bl_cb = NULL;
                        }
                    }
                    
                    /* pacotes a serem repassados para o callbox */
                    else if (bl_start_flag) {
                        uint16_t bl_cnt = 0;
                        udp_bl_timer.reset();
                        /* pacote de ERASE enviado para o cbx */
                        /* neste momento a cabeceira sabe que o servidor se comunicou com o callbox */
                        if (!(strncmp(bl_recv_buffer + 2,"\x45",1))) {
                            bl_cb = find_CB( v_cb, bl_peer );
                            if (bl_cb not_eq NULL) {
                                bl_cb->set_timeslice( bl_ts );
                                bl_cb -> cb_set_status ( cb_bootloader );
                            }
                        }
                        /* pacote de OK enviado para o cbx */
                        /* neste momento a cabeceira desaloca o timeslice do callbox  */
                        if (!(strncmp(bl_recv_buffer + 2,"\x4f\x00\x00\x00",4))) {
                            ts->return_timeslice( bl_ts );
                            bl_ts = 0;
                            if (bl_cb not_eq NULL) {
                                bl_cb->set_timeslice( 0 );
                            }
                        }
                        bl_cbx_buffer[0] = bl_ts;
                        for (bl_cnt = 0; bl_cnt < BL_SIZE; bl_cnt++) {
                            bl_cbx_buffer[bl_cnt + 1] = bl_recv_buffer[bl_cnt + 2];
                        }
                        if (debug_bootloader) {
                            pc.printf("\r\nPACOTE HDR->CBX {");
                            for (cnt = 0;cnt < BL_SIZE + 1;cnt++) {
                                if ((cnt % 30) == 0) {
                                    pc.printf("\r\n  ");
                                    pc.printf(hex16(cnt));
                                    pc.printf(" : ");
                                }
                                pc.printf(hex8(bl_cbx_buffer[cnt]));
                                pc.printf(", ");
                            }
                            pc.printf("\r\n}");
                        }
                        if (bl_cb not_eq NULL) {
                            bl_port = bl_cb->get_port();
                        } else {
                            bl_port = bl_peer;
                        }
                        send2callboxes( build_cb_package( bl_peer, bl_port, BOOTLOADER_CBX,bl_cbx_buffer, 0, BL_SIZE + 1, write_buffer) );
                    }
                }
            }
        }
        
        // verifica o socket do prompt-UDP-ETH                
        if( FD_ISSET( udp_client.get_fd(), &fdSet ) ) {
            char to_prompt_process[ PROMPT_UDP_COMMAND_SIZE ];
            for( register int i = 0; i < PROMPT_UDP_COMMAND_SIZE; i++ ) to_prompt_process[ i ] = 0;
            
            int prompt_process_msg_rcv = udp_client.receiveFrom( udp_server, to_prompt_process, ( sizeof( to_prompt_process ) - 1 ) );
            
            to_prompt_process[ prompt_process_msg_rcv ] = 0;
            if( prompt_process_msg_rcv == -1 )
            {
                if( debug_reconnect ) send_msg("Reconnect Prompt Process");
                reconnect_udp_prompt_process();
                miss_prompt_udp_rcv_pkg++;
            } 
                else if( prompt_process_msg_rcv > 0 )
            {
                udp_query = true;
                prompt_process( to_prompt_process, prompt_process_msg_rcv );
            }
        } 
        
        // verifica o socket do watchdog
        if ( FD_ISSET ( udp_wdt_client.get_fd(), &fdSet ) )
        {
            const uint16_t WAKE_MSG_SIZE = 768;
            static char wake_msg [ WAKE_MSG_SIZE ];
            
            for ( register uint16_t i = 0; i < WAKE_MSG_SIZE; i ++ ) wake_msg [ i ] = 0;
            
            Endpoint udp_wdt_server;
            
            int wake_msg_rcv = udp_wdt_client.receiveFrom( udp_wdt_server, wake_msg, sizeof( wake_msg ) );
            
            if ( dmissed_wdt ) debug_msg("wake_msg_rcv :: %d -- wake_msg :: %s", wake_msg_rcv, wake_msg );
            
            if( wake_msg_rcv == -1 )
            {
                if( debug_reconnect ) send_msg("Reconnect Extern wdt");
                reconnect_extern_wdt_socket();
                miss_wdt_send_pkg++;
            } 
                else if( wake_msg_rcv > 0 )
            {
                if( !( strncmp( wake_msg, "alive", 5 ) ) ) {
                    // Just ckeck but not set 'alive?'
                    // 'alive*' - force wdt tick right now
                    // Ckecking and set 'alive'
                    bool question_alive = ( wake_msg[ 5 ] == '?' );
                    if( wake_msg[ 5 ] == '*' ) wdt.kick();
                    
                    if ( dmissed_wdt ) if ( wake_msg [ 5 ] == '?' ) debug_msg("Recebi o alive ???");
                    
                    snprintf( wake_msg, WAKE_MSG_SIZE - 1,"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,%u:", 
                        uptime, 
                        invite_counter, 
                        external_wdt, 
                        ( wdt.WatchdogCausedReset() ) ? '1' : '0', 
                        cb_new_counter, 
                        v_cb->size(),
                        ts->remain_timeslices(), 
                        sip_socket_send_failure, 
                        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,
                        miss_closk_send_pkg
                    );
                    wake_msg[ WAKE_MSG_SIZE - 1 ] = 0;
                    
                    int send = udp_wdt_client.sendTo ( udp_wdt_server, wake_msg, strlen( wake_msg ) );
                    if( send not_eq strlen( wake_msg ) )
                    {
                        if( debug_reconnect ) debug_msg("Reconnect Extern wdt (%d, %d)", send, strlen( wake_msg ) );
                        reconnect_extern_wdt_socket ();
                        miss_wdt_send_pkg++;
                    }

                    if( ( (!question_alive) && ( cb_new_counter <= MAX_CB_IN_A_BRANCH ) && ( cb_new_counter >= 2 ) ) ) {
                        external_wdt = EXTERN_WDT_IDLE;
                        if ( dmissed_wdt ) debug_msg("kickando");
                    }
                    
                    if ( dmissed_wdt ) debug_msg("Mandei send = %d[::%s::] to [%s:%i]", send, wake_msg, udp_wdt_server.get_address (), udp_wdt_server.get_port () );
                    
                } else if( !( strncmp( wake_msg, "reset", 5 ) ) ) {
                    external_wdt = 0;

                    sprintf( wake_msg, "rst:%u:", uptime );
                    int send = udp_wdt_client.sendTo( udp_wdt_server, wake_msg, strlen( wake_msg ) );
                    if( send not_eq strlen( wake_msg ) )
                    {
                        if( debug_reconnect ) send_msg("Reconnect Extern wdt");
                        reconnect_extern_wdt_socket();
                        miss_wdt_send_pkg++;
                    }
                }
            }
        }
        
        if( FD_ISSET( clock_sock.get_fd(), &fdSet ) )
        {
            update_clock ();
        }
    }
    
    return ( ret );    
}

int show_cb_content ( void )
{
    Call_Box * cb = find_CB ( v_cb, print_this_cb );
    if ( cb not_eq NULL )
    {
        cb -> print_yourself ();
    }
        else
    {
        if( print_values )
        {
            debug_msg ("Objeto CBx ( %d ) nao encontrado", print_this_cb );
        }
            else 
        {
            send_msg ("Objeto CBx ( %d ) nao encontrado", print_this_cb );
        }
    }
    
    return ( 0 );
}

int show_cb_content_all ( void )
{
    if ( v_cb -> size () == 0 )
    {
        send_msg("known CBx :: 0");
    }
    
    for ( register uint8_t i = 0; i < v_cb->size(); i++ )
    {
        Call_Box * cb = (Call_Box *)v_cb->get_element( i );
                
        if ( cb not_eq NULL )
        {
            cb -> print_yourself ();
        }
            else
        {
            if ( print_values ) debug_msg ("Objeto CBx ( %d ) nao encontrado", i );
        }
    }
    
    return ( 0 );
}

int show_rtp ( void )
{
    send_msg(":: RTP :: %u", v_cb->size() );
    
    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 );
    }   
    
    for ( register uint8_t i = 0; i < v_cb->size(); i++ )
    {
        Call_Box * cb = find_CB( v_cb, ext_list[ i ] );
        if( cb not_eq NULL )
        {
            send_msg("CBX ( %d,  %d ) - SIP  ( %d,  %d ) - RTP ( %d )", 
                cb -> get_ext (),
                cb -> get_port (),
                cb -> get_sip_ext (), 
                cb -> get_sip_port (), 
                cb -> get_rtp_port ()
            );
        }
    }
    
    return ( 0 );
}

int fuck_rtp ( Vector * v_cb )
{
    Call_Box * cb = find_CB( v_cb, frtp_target );
    if ( cb not_eq NULL )
    {
        cb -> set_rtp_port ( -1008789032 );
    }
        else
    {
        debug_msg("frtp fail");
    }
    
    return ( 0 );
}

int show_hex_cb_content ( void )
{
    uint8_t * ptr = ( uint8_t * ) find_CB ( v_cb, print_hex_this_cb );    
    
    if ( ptr not_eq NULL )
    {
        send_msg ("Values :: %p\r\n", ( void *) ptr );            
        for ( register int i = 0; i < sizeof( Call_Box ); i++ )
        {
            if( debug_uart3 ) pc.printf("%x", *ptr++ );
            
            if ( ( i % 32 ) == 0 )
            {
                if( i not_eq 0 )
                {
                    if( debug_uart3 ) pc.printf("\n\r> ");
                }  
                    else
                {
                    if( debug_uart3 ) pc.printf(" ");
                }
            }        
                else
            {
                if( debug_uart3 ) pc.printf(" ");
            }
        }
        if ( debug_uart3 ) pc.printf("\n\r> ");
        
        if ( tcp_session ) {
            char aux[ ( sizeof( Call_Box ) * 3 ) + 3 ];
            
            for ( register int i = 0; i < ( sizeof( Call_Box ) * 3 ) + 3 ; i++ ) aux [ i ] = 0;
            
            uint8_t * ptr = ( uint8_t * ) find_CB ( v_cb, print_hex_this_cb );
            
            for ( register int i = 0; i < sizeof( Call_Box ); i++ )
            {
                char tmp[ 16 ];
                sprintf( tmp, "%x ", *ptr++ );  
                strcat( aux, tmp );
            }
            
            strcat( aux, "\n\r\0" );
            tcp_client.send_all( ( char *)aux, strlen( (char * )aux ) );
            tcp_client.send_all( "\r\n> ", strlen( "\r\n> " ) );
        }
    }
        else
    {
        if ( print_values ) debug_msg ("Objeto CBx ( %d ) nao encontrado", print_this_cb );
    }
    
    return ( 0 );
}

int show_hex_cb_content_all ()
{
    if ( v_cb -> size () == 0 )
    {
        send_msg("known CBx :: 0");    
    }
    
    for ( register uint8_t j = 0; j < v_cb->size(); j++ )
    {
        uint8_t * ptr = ( uint8_t * ) v_cb->get_element( j );
                    
        if ( ptr not_eq NULL )
        {
            send_msg ("Values :: %p\r\n", ( void *) ptr );
            for ( register int i = 0; i < sizeof( Call_Box ); i++ )
            {
                if( debug_uart3 ) pc.printf("%x", *ptr++ );
                
                if ( ( i % 32 ) == 0 )
                {
                    if( i not_eq 0 )
                    {
                        if( debug_uart3 ) pc.printf("\n\r> ");
                    }  
                        else
                    {
                        if( debug_uart3 ) pc.printf(" ");
                    }
                }        
                    else
                {
                    if( debug_uart3 ) pc.printf(" ");
                }
            }
            if ( debug_uart3 ) pc.printf("\n\r> ");
            
            if ( tcp_session ) {
                char aux[ ( sizeof( Call_Box ) * 3 ) + 3 ];
                
                for ( register int i = 0; i < ( sizeof( Call_Box ) * 3 ) + 3 ; i++ ) aux [ i ] = 0;
                
                uint8_t * ptr = ( uint8_t * ) v_cb->get_element( j );
                
                for ( register int i = 0; i < sizeof( Call_Box ); i++ )
                {
                    char tmp[ 16 ];
                    sprintf( tmp, "%x ", *ptr++ );  
                    strcat( aux, tmp );
                }
                
                strcat( aux, "\n\r\0" );
                tcp_client.send_all( ( char *)aux, strlen( (char * )aux ) );
                tcp_client.send_all( "\r\n> ", strlen( "\r\n> " ) );
            }
        }
            else
        {
            if ( print_values ) 
            {
                debug_msg ("Objeto CBx ( %d ) nao encontrado", j );
            }
                else 
            {
                send_msg ("Objeto CBx ( %d ) nao encontrado", j );
            }
        }
    }
    
    return ( 0 );    
}


int show_cB_sip ( void )
{
    Call_Box * cb = find_CB ( v_cb, print_this_sip );
    
    if ( cb not_eq NULL )
    {
        if( cb -> sip_print_yourself () == -1 )
        {
            if( print_values )
            {
                debug_msg("Sip param of %d equals NULL", print_this_sip );
            }
                else 
            {
                send_msg("Sip param of %d equals NULL", print_this_sip );
            }
        }
    }
        else
    {
        if ( print_values ) 
        {
            debug_msg ("Objeto CBx ( %d ) nao encontrado", print_this_cb );
        }
            else 
        {
            send_msg ("Objeto CBx ( %d ) nao encontrado", print_this_cb );
        }                
    }
    
    return ( 0 );    
}
int show_cB_sip_all ( void )
{    
    if ( v_cb -> size () == 0 )
    {
        send_msg("known CBx :: 0");
    }
    
    for ( register uint8_t i = 0; i < v_cb->size(); i++ )
    {
        Call_Box * cb = (Call_Box *)v_cb->get_element( i );
                
        if ( cb not_eq NULL )
        {
            if ( cb -> sip_print_yourself () == -1 )
            {
                if ( print_values )
                {
                    debug_msg ("Sip param of %d equals NULL", print_this_sip );
                }
                    else 
                {
                    send_msg ("Sip param of %d equals NULL", print_this_sip );
                }
            }
        }
            else
        {
            if( print_values )
            {
                debug_msg ("CBx %d not found", print_this_sip );
            }
                else 
            {
                send_msg ("CBx %d not found", print_this_sip );
            }
        }
    }
    return ( 0 );    
}

int show_cB_hex_sip ( void )
{
    uint8_t * ptr = NULL;
    
    Call_Box * cb = find_CB ( v_cb, print_hex_this_sip );
    if( cb not_eq NULL )
    {
        ptr = ( uint8_t * ) cb -> get_sip ();
    }

    if ( ptr not_eq NULL )
    {
        send_msg ("Values :: %p\r\n", ( void *) ptr );
        for ( register int i = 0; i < sizeof( Sip ); i++ )
        {
            if( debug_uart3 ) pc.printf("%x", *ptr++ );
            
            if ( ( i % 32 ) == 0 )
            {
                if( i not_eq 0 )
                {
                    if( debug_uart3 ) pc.printf("\n\r> ");
                }  
                    else
                {
                    if( debug_uart3 ) pc.printf(" ");
                }
            }        
                else
            {
                if( debug_uart3 ) pc.printf(" ");
            }
        }
        if ( debug_uart3 ) pc.printf("\n\r> ");
        
        if ( tcp_session ) {
            char aux[ ( 32 * 3 ) + 5 ];
            
            for ( register int i = 0; i < ( 32 * 3 ) + 5 ; i++ ) aux [ i ] = 0;
            
            ptr = NULL;
    
            print_hex_sip_var = false;
            Call_Box * cb = find_CB ( v_cb, print_hex_this_sip );
            if( cb not_eq NULL )
            {
                ptr = ( uint8_t * ) cb -> get_sip ();
            }
    
            if ( ptr not_eq NULL )
            {
                bool finished = false;
                volatile int i = 0;
                int count = 0;
                Timer dont_overwrite_tcp_buffer;
                dont_overwrite_tcp_buffer.reset ();
                dont_overwrite_tcp_buffer.start ();
                
                while ( !finished )
                {
                    if( dont_overwrite_tcp_buffer.read_ms () >= 500 )
                    {
                        dont_overwrite_tcp_buffer.reset();
                        for ( ; i < sizeof( Sip ); i++ )
                        {
                            char tmp[ 16 ];
                            sprintf( tmp, "%x ", *ptr++ );  
                            strcat( aux, tmp );
                            count++;
                            
                            if ( count >= 32  )
                            {
                                count = 0;
                                i++;
                                break;
                            }
                        }                                
                        strcat ( aux, "\n\r\0" );
                        tcp_client.send_all ( ( char *)aux, strlen( (char * )aux ) );
                        if ( i >= sizeof ( Sip ) ) finished = true;
                        strcpy ( aux, "\0" );
                    }
                }
                dont_overwrite_tcp_buffer.reset();
                dont_overwrite_tcp_buffer.stop();
                tcp_client.send_all ( "\r\n> ", strlen( "\r\n> " ) );
            }
        }
    }
        else
    {
        if ( print_values ) debug_msg ("Objeto CBx ( %d ) nao encontrado", print_this_cb );
    }
    
    
    return ( 0 );    
}

int show_rtp_on_call ( void )
{
    send_msg(":: CAll RTP :: %u", v_call->size() );
    
    for( register uint8_t i = 0; i < v_call->size(); i++ ) {
        VZ_call * call = ( VZ_call * )v_call->get_element( i );
        if( call not_eq NULL )
        {
            send_msg("CBX ( %d,  %d ) - Server ( %d,  %d )", 
                call->get_cb_ext(),
                call->get_cb_port(), 
                call->get_rtp_server_ext(), 
                call->get_rtp_server_port()
            );
        }
    }
    
    return ( 0 );    
}

int show_call ( void )
{
    VZ_call * call = find_Call ( v_call, print_this_call );
    
    if ( call not_eq NULL )
    {
        send_msg ("Values :: %p\r\n", ( void *) call );
        call -> print_yourself ();
    }
        else
    {            
        if( print_values )
        {
            debug_msg("Call %d not found", print_this_call );
        }
            else 
        {
            send_msg("Call %d not found", print_this_call );
        }
    }
    
    return ( 0 );
}

int show_hex_call ( void )
{
    VZ_call * call = find_Call ( v_call, print_hex_this_call );
            
    uint8_t * ptr = NULL;
    if( call not_eq NULL )
    {
        ptr = ( uint8_t * ) call;
    }

    if ( ptr not_eq NULL )
    {
        send_msg ("Values :: %p\r\n", ( void *) ptr );
        for ( register int i = 0; i < sizeof( VZ_call ); i++ )
        {
            if( debug_uart3 ) pc.printf("%x", *ptr++ );
            
            if ( ( i % 32 ) == 0 )
            {
                if( i not_eq 0 )
                {
                    if( debug_uart3 ) pc.printf("\n\r> ");
                }  
                    else
                {
                    if( debug_uart3 ) pc.printf(" ");
                }
            }        
                else
            {
                if( debug_uart3 ) pc.printf(" ");
            }
        }
        if ( debug_uart3 ) pc.printf("\n\r> ");
        
        if ( tcp_session ) {
            char aux[ ( 32 * 3 ) + 5 ];
            
            for ( register int i = 0; i < ( 32 * 3 ) + 5 ; i++ ) aux [ i ] = 0;
            
            ptr = NULL;
    
            VZ_call * call = find_Call ( v_call, print_hex_this_call );
            
            uint8_t * ptr = NULL;
            if( call not_eq NULL )
            {
                ptr = ( uint8_t * ) call;
            }
    
            if ( ptr not_eq NULL )
            {
                bool finished = false;
                volatile int i = 0;
                int count = 0;
                Timer dont_overwrite_tcp_buffer;
                dont_overwrite_tcp_buffer.reset ();
                dont_overwrite_tcp_buffer.start ();
                
                while ( !finished )
                {
                    if( dont_overwrite_tcp_buffer.read_ms () >= 20 )
                    {
                        dont_overwrite_tcp_buffer.reset();
                        for ( ; i < sizeof( VZ_call ); i++ )
                        {
                            char tmp[ 16 ];
                            sprintf( tmp, "%x ", *ptr++ );  
                            strcat( aux, tmp );
                            count++;
                            
                            if ( count >= 32  )
                            {
                                count = 0;
                                i++;
                                break;
                            }
                        }                                
                        strcat ( aux, "\n\r\0" );
                        tcp_client.send_all ( ( char *)aux, strlen( (char * )aux ) );
                        if ( i >= sizeof ( VZ_call ) ) finished = true;
                        strcpy ( aux, "\0" );
                    }
                }
                dont_overwrite_tcp_buffer.reset();
                dont_overwrite_tcp_buffer.stop();
                tcp_client.send_all ( "\r\n> ", strlen( "\r\n> " ) );
            }
        }
    }
        else
    {   
        if( print_values )
        {
            debug_msg("Call %d not found", print_this_call );
        }
            else 
        {
            send_msg("Call %d not found", print_this_call );
        }
    }
    
    return ( 0 );    
}


int show_cb_rtp ( void )
{
    VZ_call * call = find_Call ( v_call, print_hex_this_rtp );
            
    uint8_t * ptr = NULL;
    if( call not_eq NULL )
    {
        ptr = ( uint8_t * ) call -> check_rtp ();
    }

    if ( ptr not_eq NULL )
    {
        send_msg ("Values :: %p\r\n", ( void *) ptr );
        for ( register int i = 0; i < sizeof( RTP ); i++ )
        {
            if( debug_uart3 ) pc.printf("%x", *ptr++ );
            
            if ( ( i % 32 ) == 0 )
            {
                if( i not_eq 0 )
                {
                    if( debug_uart3 ) pc.printf("\n\r> ");
                }  
                    else
                {
                    if( debug_uart3 ) pc.printf(" ");
                }
            }        
                else
            {
                if( debug_uart3 ) pc.printf(" ");
            }
        }
        if ( debug_uart3 ) pc.printf("\n\r> ");
        
        if ( tcp_session ) {
            char aux[ ( 32 * 3 ) + 5 ];
            
            for ( register int i = 0; i < ( 32 * 3 ) + 5 ; i++ ) aux [ i ] = 0;
            
            ptr = NULL;
    
            VZ_call * call = find_Call ( v_call, print_hex_this_rtp );
            
            uint8_t * ptr = NULL;
            if( call not_eq NULL )
            {
                ptr = ( uint8_t * ) call -> check_rtp ();
            }
    
            if ( ptr not_eq NULL )
            {
                bool finished = false;
                volatile int i = 0;
                int count = 0;
                Timer dont_overwrite_tcp_buffer;
                dont_overwrite_tcp_buffer.reset ();
                dont_overwrite_tcp_buffer.start ();
                
                while ( !finished )
                {
                    if( dont_overwrite_tcp_buffer.read_ms () >= 20 )
                    {
                        dont_overwrite_tcp_buffer.reset();
                        for ( ; i < sizeof( RTP ); i++ )
                        {
                            char tmp[ 16 ];
                            sprintf( tmp, "%x ", *ptr++ );  
                            strcat( aux, tmp );
                            count++;
                            
                            if ( count >= 32  )
                            {
                                count = 0;
                                i++;
                                break;
                            }
                        }                                
                        strcat ( aux, "\n\r\0" );
                        tcp_client.send_all ( ( char *)aux, strlen( (char * )aux ) );
                        if ( i >= sizeof ( RTP ) ) finished = true;
                        strcpy ( aux, "\0" );
                    }
                }
                dont_overwrite_tcp_buffer.reset();
                dont_overwrite_tcp_buffer.stop();
                tcp_client.send_all ( "\r\n> ", strlen( "\r\n> " ) );
            }
        }
    }
        else
    {   
        if( print_values )
        {
            debug_msg("Call %d not found", print_this_rtp );
        }
            else 
        {
            send_msg("Call %d not found", print_this_rtp );
        }
    }
    
    return ( 0 );    
}

int show_cb_hex_rtp ( void )
{
    VZ_call * call = find_Call ( v_call, print_this_rtp );
    
    if ( call not_eq NULL )
    {
        if ( call -> check_rtp () not_eq NULL )
        {
            send_msg ("Values :: %p\r\n", ( void *) call -> check_rtp () );
            call -> rtp_print_yourself ();
        }
            else
        {
            if( print_values )
            {
                debug_msg("Call->RTP %d not found", print_this_rtp );
            }
                else 
            {
                send_msg("Call->RTP %d not found", print_this_rtp );
            }       
        }
    }
        else
    {            
        if( print_values )
        {
            debug_msg("Call->RTP %d not found", print_this_rtp );
        }
            else 
        {
            send_msg("Call->RTP %d not found", print_this_rtp );
        }
    }
    
    return ( 0 );    
}


int reset_stats_cks ( void )
{
    pkg_cksok = 0;
    pkg_ckserr = 0;
    pkg_zero = 0;
    out_of_range = 0;
    missed_pkg = 0;
    delayed_pkg_to_cb = 0;
    cpld_pkg_tx_counter = 0;
    cpld_pkg_rx_counter = 0;
    
    return ( 0 );
}

int show_cb_stats ( void )
{
    send_msg( 
        "\r\n"
        "   PKG_CKS OK: %d ( %003.2f )\r\n"
        "   PKG_CKS ERR: %d ( %003.2f )\r\n"
        "   PKG_0: %d ( %003.2f )\r\n"
        "   Out_of_range: %d ( %003.2f )\r\n"
        "   Miss_Pkg: %d\r\n"
        "   TX_delayed: %d\n\r"
        "   TX_Counter: %d\n\r"
        "   RX_Counter: %d\r\n",
        pkg_cksok, ( cpld_pkg_rx_counter  == 0 ) ? 0.00 : ( (  double ) pkg_cksok / cpld_pkg_rx_counter ) * 100, 
        pkg_ckserr, ( cpld_pkg_rx_counter  == 0 ) ? 0.00 : ( ( double ) pkg_ckserr / cpld_pkg_rx_counter ) * 100, 
        pkg_zero, ( cpld_pkg_rx_counter  == 0 ) ? 0.00 : ( ( double ) pkg_zero / cpld_pkg_rx_counter ) * 100, 
        out_of_range, ( cpld_pkg_rx_counter  == 0 ) ? 0.00 : ( ( double ) out_of_range / cpld_pkg_rx_counter ) * 100, 
        missed_pkg, 
        delayed_pkg_to_cb, 
        cpld_pkg_tx_counter, 
        cpld_pkg_rx_counter 
    );
    
    return ( 0 );   
}


int reset_missed_send_udp ( void )
{
    miss_fw_send_pkg = 0;                                                                                                                 
    miss_prompt_udp_send_pkg = 0;                                                                                                         
    miss_sip_registry_send_pkg = 0;                                                                                                       
    miss_sip_invite_send_pkg = 0;                                                                                                         
    miss_sip_bye_send_pkg = 0;                                                                                                            
    miss_sip_unregistry_send_pkg = 0;                                                                                                     
    miss_sip_ok_send_pkg = 0;                                                                                                             
    miss_sip_rcv_bye_send_pkg = 0;
    miss_wdt_send_pkg = 0;
    miss_prompt_udp_send_pkg = 0;
    miss_ftp_udp_send_pkg = 0;
    miss_prompt_udp_rcv_pkg = 0;
    
    return ( 0 );
}

int show_missed_send_udp_pkg ( void )
{
    send_msg(   "\r\nMissed pkgs ::\r\n "
                "FW: %d\r\n "
                "Prompt UDP %d\r\n "
                "Registry %d\r\n "
                "Invite %d\r\n "
                "Bye %d\r\n "
                "Unregistry %d\r\n "
                "UDP incoming ( invite ans ) %d\r\n "
                "UDP incoming ( bye from * ) %d\r\n "
                "Wdt [ alive | rst ] %d\r\n "
                "Rcv prompt %d\r\n "
                "[ debug | send ]_msg %d\r\n "
                "RTP %d\r\n", 
        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_prompt_udp_rcv_pkg,
        miss_ftp_udp_send_pkg 
    );
    
    return ( 0 );
}

int invite_ack_to_cb_handler ( Vector * v_cb, Vector * v_call )
{    
    static int retry_invite_pkg = 0;
    bool need_retry = false;
    Call_Box * cb = NULL;

    for ( register int i = 0; i < v_cb -> size (); i++ )
    {
        retry_invite_pkg++;
        if ( retry_invite_pkg >= v_cb->size () ) retry_invite_pkg = 0;
        
        cb = (Call_Box * )v_cb -> get_element ( i );
        if ( cb not_eq NULL )
        {
            if ( ( cb -> get_status () == cb_ringing ) or ( cb -> get_status () == cb_trying ) or ( cb -> get_status () == cb_on_call ) )
            {
                need_retry = true;
                break;
            }
        }
    }
    
    if ( need_retry )
    {
        if ( cb -> get_invite_response () == false )
        {
            buffer [ TIMESLICE_PLACE ] = cb -> get_timeslice ();
            
            do_not_show_this_invite_pkg = true;
            
            send2callboxes ( build_cb_package ( cb -> get_ext (), cb -> get_port (), INVITE, ( char * )buffer,
               cb -> msg_id_update (), CB_BUFFER_SIZE - VZ_HEADER_OFFSET, write_buffer ) );

            //if ( debug_invite ) debug_msg ("[%d] resend invite OK to Cbx : ( %d,  %d )", cb -> get_ext (), cb -> get_ext (), cb -> get_port () );
        } 
        
        if ( find_Call ( v_call, cb->get_ext () ) == NULL )
        {
        
            if ( ( ( cb -> get_status () == cb_ringing ) or ( cb -> get_status () == cb_trying ) ) )
            {
                    char rtp_src_tmp_write_buffer [ CB_BUFFER_SIZE ];
                    uint8_t rtp_dst_tmp_write_buffer [ CB_BUFFER_SIZE ];
                    
                    for ( register int i = 0; i < RTP_MSG_SIZE; i++ ) rtp_src_tmp_write_buffer [ i ] = 0x00;
                    
                    send2callboxes ( build_cb_package ( cb -> get_ext (), cb -> get_port (), AUDIO, 
                        rtp_src_tmp_write_buffer, AUDIO, RTP_MSG_SIZE, rtp_dst_tmp_write_buffer ) );
            } else {
                if ( cb->get_invite_retry_count() == 0 )
                {
                    cb->set_msg_id( ( cb->get_msg_id() + 1 ) & ~BIT7 );

                    for ( register uint8_t i = 0; i < v_call->size(); i++ )
                    {
                        VZ_call * call = ( VZ_call * )v_call->get_element( i );
                        if( call->get_cb_ext() == cb->get_ext() )
                        {
                            v_call->remove_element( i );
                            if( call not_eq NULL ) delete( call );
                            break;
                        }
                    }
                    
                    ts->return_timeslice( cb->call_end () );
                    
                    if( debug_invite ) debug_msg( "[%d]-- No audio pkgs --", cb->get_ext () );
                }
            }
        }
    }
    
    return ( 0 );    
}

int check_audio_from_ast ( Vector * v_cb, Vector * v_call )
{
    for( register uint8_t i = 0; i < v_call->size(); i++ )
    {
        VZ_call * call = ( VZ_call * ) v_call -> get_element ( i );
        if ( call not_eq NULL )
        {
            int length = 0;
            char * tmp = call -> get_eth_message ( &length );
            if( tmp not_eq NULL )
            {
                int cb_port = 0xffff;
                Call_Box * cb = find_CB ( v_cb, call -> get_cb_ext () );

                if( cb not_eq NULL ) 
                {
                    cb_port = cb -> get_port ();
                    
                    if ( drop_rtp_from_ast_pkg )
                    {
                        led1 = !led1;
                    }
                        else
                    {
                        uint8_t * pkg2cb = build_cb_package ( call -> get_cb_ext (), cb_port, AUDIO,
                            tmp, AUDIO, length, write_buffer );
                            
                        send2callboxes( pkg2cb );
                    }
                    
                } else if ( debug_main ) debug_msg ("[%d] received missed package -- Type :: %i", ext, type );
            }
        }
    }

    return ( 0 );    
}

int wake_up_or_refresh_handler ( Vector * v_cb )
{
    int return_value = 0;
    
    if( timer_sync_refresh.read_ms() > 250 * 2 )
    {
        timer_sync_refresh.reset();
    
        static uint8_t time_to_mode = TIME_TO_REFRESH;
    
        if ( time_to_mode == TIME_TO_REFRESH ){
            time_to_mode = TIME_TO_WAKE_UP;
            if ( !do_not_refresh ) return_value = refresh ( v_cb );
        } else {
            time_to_mode = TIME_TO_REFRESH;
            if ( wake_all ) if ( v_call->size() == 0 ) wake_all_up ( v_cb );
        }
    }
    
    return ( return_value );
}

int check_sip_messages_from_ast ( Vector * v_cb, Vector * v_call )
{
    // check sip messages only for cbx in call ?
    int ext_to__be_removed = sip_manager( v_cb );
    if( ext_to__be_removed > 0 ) {
        Call_Box * cb = find_CB( v_cb, ext_to__be_removed );
        if( cb not_eq NULL ) {
            //if( cb->status == cb_on_call ) // poderia ser if( cb->status not_eq cb_idle ) ???
            if ( cb -> get_status () == cb_on_call )
            {
                buffer[ TIMESLICE_PLACE ] = 0;

                for( register uint8_t i = 0; i < v_call->size(); i++ ) {
                    VZ_call * call = ( VZ_call * )v_call->get_element( i );
                    if( call->get_cb_ext() == ext_to__be_removed ) {
                        v_call->remove_element( i );
                        delete( call );
                    }
                }
                
                ts->return_timeslice( cb->call_end ( false ) );

                send2callboxes( build_cb_package( cb->get_ext (), cb->get_port (), CB_BYE,
                    ( char * )buffer, cb->get_msg_id(), CB_BUFFER_SIZE - VZ_HEADER_OFFSET, write_buffer ) );
                
                if( debug_invite ) debug_msg("[%d] Received Bye from *", cb->get_ext () );
            }
        } else if( debug_main ) debug_msg("[%d] Missed bye request", ext_to__be_removed );
    }
    
    return ( 0 );    
}

int check_for_runaways_ts ( Vector * v_cb, Timeslice * ts )
{
    if( ( v_call->size() == 0 ) && ( ts->remain_timeslices() not_eq MAX_TIMESLICES ) ) {
        bool ts_reset = true;
        for( register uint8_t i = 0; i < v_cb->size(); i++ ) {
            uint16_t cb_status = ((Call_Box *)v_cb->get_element( i ))->get_status();
            uint16_t cb_sip_status = ((Call_Box *)v_cb->get_element( i ))->get_sip_status();
            
            if  ((cb_status not_eq cb_idle) and (cb_sip_status not_eq sip_idle)) {
                ts_reset = false;
                break;
            }
            
        }
        if( ts_reset && !bl_start_flag )
        {
            if( debug_invite ) debug_msg("Resetando TS");
            ts->reset();
        }
    }

    return ( 0 );    
}

int show_wdt_status ( void )
{
    send_msg("lpc_low_level_input_counter :: %d", lpc_low_level_input_counter );
    
    lpc_low_level_input_counter = 0;

    if( eth_status == 0 ) {
        send_msg( "Wdt last reset: %s - status_eth :: Connected - Extern Wdt idle for :: %3d sec ( %3d ) - Rx from CBx idle for :: %3d sec ( %3d )",
                  ( wdt.WatchdogCausedReset() ) ? "true" : "false",
                  EXTERN_WDT_IDLE - external_wdt,
                  EXTERN_WDT_IDLE,
                  RX_CB_IDLE - pkg_wdt,
                  RX_CB_IDLE
                );
    } else {
        send_msg( "Wdt last reset: %s - status_eth :: Disconnected :: since %3d sec - Extern Wdt idle for :: %3d sec ( %3d ) - Rx from CBx idle for :: %3d sec ( %3d )",
                  ( wdt.WatchdogCausedReset() ) ? "true" : "false",
                  ETH_CONNECT_TIMEOUT - eth_wdt,
                  EXTERN_WDT_IDLE - external_wdt,
                  EXTERN_WDT_IDLE,
                  RX_CB_IDLE - pkg_wdt,
                  RX_CB_IDLE
                );
    }

    return ( 0 );    
}


int wdt_update ( void )
{
    uptime++;
            
    current_time++;

    if ( wdt_show ) debug_wdt = true;

    if ( external_wdt ) external_wdt--;
    if ( pkg_wdt ) pkg_wdt--;
    if ( eth_wdt ) eth_wdt--;

    if ( eth_wdt && external_wdt && pkg_wdt ){
        wdt.kick();
        return ( 0 );
    }
    
    return ( 1 );
}

int check_for_unwanted_rtp_ports ( Vector * v_cb )
{
    for ( register uint8_t i = 0; i < v_cb->size(); i++ )
    {
        Call_Box * cb = (Call_Box *) v_cb->get_element (i);
        if ( cb not_eq NULL )
        {
            if (  ( cb->get_status () == cb_idle ) && ( cb->get_sip_status () == sip_idle ) && ( cb -> is_rtp_timer_timeout () ) )
            {
                if ( debug_reset_rtp ) debug_msg( "[%d] rtp reset", cb -> get_ext () );
                cb -> cb_set_status( cb_idle );
                cb -> set_sip_status ( sip_idle );
                cb -> reset_rtp_timer ();
                cb -> set_rtp_port ( 0 );           
            }
        }
    }
    return ( 0 );    
}


int process_received_pkg_from_cbx ( void )
{   
    // short path
    if ( buffer_from_cb_ptr [ TYPE_PLACE ] == AUDIO )
    {
        xmemcpy ( buffer, buffer_from_cb_ptr, CB_BUFFER_SIZE );
        status = WAITING;
        missed_pkg--;
    }
        else
    // long path
    {
        xmemcpy ( cb_rx_buffer, buffer_from_cb_ptr, CB_BUFFER_SIZE );
        status = WAITING;
        missed_pkg--;
        xmemcpy ( buffer, cb_rx_buffer, CB_BUFFER_SIZE );
  
        if ( debug_show_rx_cpld )
        {
            char str [ 256 ];
            strcpy ( str, "RX :: \n\r" );
            
            for ( register uint16_t i = 0; i < 32; i++ )
            {
                char tmp [ 8 ];
                sprintf ( tmp, "%02x ", cb_rx_buffer [ i ] );
                strcat ( str, tmp );
            }
            
            strcat ( str, "\n\r " );
            
            send_msg ( "%s", str );
        }            
    }

    data = parse_vz_pkg ( &ext, &port, &type, buffer );

    if ( data not_eq NULL )
    {   
        if ( min_ext == 0 ) min_ext = ext;

        if ( ext > max_ext ) max_ext = ext;

        if ( ext < min_ext ) min_ext = ext;
        
        if ( debug_fw ) { fw_cbx_pkg ( ext, ( char *)buffer ); }
        
        if ( type == TELEMETRY )
        {
            telemetry_counter++;
            if ( debug_telemetry ) show_last_rx = true;
        }

        if( type not_eq AUDIO )
        {
            if ( debug_cb_rx ) { send_msg ("[%d %d] -- Type :: %d", ext, port, type ); }
            
            if( 
                type == TELEMETRY or
                type == CB_STATS or
                type == FW1 or
                type == FW2 or
                type == FW3 or
                type == FW4 or
                type == FW5 or
                type == FW6
             ) type = FW;
            
            if ( debug_sqn ) { send_msg ("[%d %d] -- Type :: %d -- seq_num :: %u", ext, port, type, cb_tx_buffer [ SEQ_NUM_PLACE ] ); }

            Call_Box * cb = find_CB ( v_cb, ext );
            if ( cb not_eq NULL ) 
            {
                if ( data[ 0 ] bitand BIT7 ) 
                {
                    if ( type == BOOT )
                    {
                        send2callboxes( build_cb_package( ext, port, REGISTRY,
                            ( char * )data, cb->get_msg_id(), CB_BUFFER_SIZE - VZ_HEADER_OFFSET, write_buffer ) );
                    } else {
                        if ( debug_main ) debug_msg("[%d] Received ack pkg with seq_num %d", ext, data[ 0 ] );

                        switch ( type )
                        {
                            case INVITE : {
                                if ( debug_main or debug_invite ) debug_msg ("[%d] Invite ACK - msg_id %d -- Cbx seqNum %d", ext, cb->get_msg_id(), data[ 0 ] );
                                break;
                            }
                            case CB_BYE : {
                                if ( debug_main or debug_invite ) debug_msg ("[%d] BYE ACK - msg_id %d", ext, cb->get_msg_id() );
                                cb -> set_bye_response_ok ();
                                break;
                            }
                            case REGISTRY : {
                                if ( debug_main or debug_aging ) debug_msg ("[%d] Registry ACK - msg_id %d", ext, cb->get_msg_id() );
                                break;
                            }
                            default : {
                                if ( debug_main or debug_aging ) debug_msg ("[%d] ACK msg_id :: %d :: type %d", ext, cb->get_msg_id(), type );
                            }
                        }
                        if ( type not_eq REGISTRY and type not_eq CB_BYE and type not_eq INVITE ) type = DO_NOTHING;
                        if ( type == CB_BYE )
                        {
                            VZ_call * call = find_Call ( v_call, ext );
                            if ( call not_eq NULL )
                            {
                                if ( call -> get_elapsed_time () < 120000 )
                                {
                                    if ( debug_invite ) debug_msg("[%d] ack bye ignored", ext );
                                    type = DO_NOTHING;
                                }
                            }
                        }
                    }
                }
            }
        }
    } else type = DO_NOTHING;
    
    return 0;
}

void update_all_cb_timer ( Vector * v_cb )
{
    if ( v_cb == NULL ) return;
    
    for( register uint8_t i = 0; i < v_cb->size(); i++ )
    {
        Call_Box * cb = ( Call_Box * )v_cb->get_element( i );
        if ( cb not_eq NULL ) cb -> update_time ();
    }
}

int init_hello ( void )
{
    hello_sync.start ();
    hello_times = 0;
    return ( 0 );
}

void send_hello_to_cbx ( void )
{   
    if ( hello_times >= 3 ){
        hello_sync.stop ();
        hello_sync.reset ();
        dont_say_hello_again = true;
    }
    
    if ( ( !dont_say_hello_again ) && ( hello_sync.read () > 3 ) && ( hello_times < 3 ) )
    {
        hello_times++;
        
        char cmd_msg [ CB_BUFFER_SIZE ] = "pend\r";
        
        if ( debug_hello ) debug_msg("Enviando pend_all nro [ %i ]", hello_times ); 
        
        send2callboxes( build_cb_package( BROADCAST_EXT, BROADCAST_EXT, PROMPT, cmd_msg, ( 0x11 + hello_times ), CB_BUFFER_SIZE - VZ_HEADER_OFFSET, write_buffer ) );
        
        hello_sync.reset ();
    }
}

void show_hello_status_function ( void )
{
    send_msg ("hello_sync.read :: %d -- hello_times :: %u", ( int ) hello_sync.read (), hello_times );        
}

void show_last_rx_pkg_from_cbx ( void )
{
    char str [ 256 ] = "";
    
    for ( register uint16_t i = 0; i < CB_BUFFER_SIZE; i++ )
    {
        char tmp[ 8 ];
    
        sprintf ( tmp, "%02x", cb_rx_buffer [ i ] );
        
        strcat ( str, tmp );
        
        if ( ( i not_eq 0 ) && !( ( i + 1 ) % 25 ) )
        { 
            send_msg ( "%s", str );
            strcpy ( str, "" );
        } 
        
        else { strcat ( str, " " ); }
    }
    
    send_msg ( "%s", str );
}

void show_last_tx_pkg_from_cbx ( void )
{   
    char str [ 256 ] = "";
    
    for ( register uint16_t i = 0; i < CB_BUFFER_SIZE; i++ )
    {
        char tmp[ 8 ];
    
        sprintf ( tmp, "%02x", cb_tx_buffer [ i ] );
        
        strcat ( str, tmp );
        
        if ( ( i not_eq 0 ) && !( ( i + 1 ) % 25 ) )
        { 
            send_msg ( "%s", str );
            strcpy ( str, "" );
        } 
        
        else { strcat ( str, " " ); }
    }
    
    send_msg ( "%s", str );
}

/* Funcao para leitura da fonte de alimentacao e aviso ao servidor */
void check_power_source ( void )
{
    static uint8_t samples = 0, warn_back = 0, wait_to_warn = 0; 
    //static uint16_t wait_to_warn = 0;

    pwr_src_timer.stop();
    pwr_src_timer.reset();

    if (pwr_src_in) {
        if (samples < 8) samples++;
    } else {
        if (samples > 0) samples--;
    }
    
    if (wait_to_warn) wait_to_warn--;
    
    if (samples >= 8) {
        pwr_src_status = 1;
        if (!wait_to_warn) {         
            wait_to_warn = 255;
            warn_back = 1;
            pwr_src_client.sendTo( pwr_src_server, "mainpowerisdown", strlen( "mainpowerisdown" ) );
            debug_msg( "Main power is DOWN!" );
        } else {
            wait_to_warn--;
        }
    }
    if ((samples == 0) and (warn_back)) {
        pwr_src_status = 0;
        warn_back = 0;
        wait_to_warn = 0;
        pwr_src_client.sendTo( pwr_src_server, "mainpowerisback", strlen( "mainpowerisback" ) );
        debug_msg( "Main power is BACK!" );
    }
    
    pwr_src_timer.start();
}