voltando a versao de n aberturas e fechamentos de sockets

Dependencies:   EthernetInterface NTPClient mbed-rtos_old mbed

Fork of header_main_public by VZTECH

main.cpp

Committer:
klauss
Date:
2014-09-09
Revision:
0:4d17cd9c8f9d
Child:
1:a1758104fa1d

File content as of revision 0:4d17cd9c8f9d:

#include "bits.h"
#include "utils.h"
#include "configs.h"
#include "UART3Interrupt.h"
#include "parallelcpld.h"

#include "debug.h"
#include "utils.h"


// for aditional debugs
#define on_work

/*
#define set_status(a,b) _set_status(a,b)
#define _set_status(a,b) { \
 a = b; \
 sprintf( debug_msg, "-- State == %d -- Line %d", a, __LINE__ ); \
 debug.sendTo( debug_server, debug_msg, strlen( debug_msg ) ); \
}
#define whereami() _whereami()
#define _whereami() { \
 sprintf( debug_msg, "-- whereami %d", __LINE__ ); \
 debug.sendTo( debug_server, debug_msg, strlen( debug_msg ) ); \
}
*/
volatile uint8_t status = 0x00;

bool debug_bool = true;

int main(){
    start_cpld();
    config_lpc();
    
    /* referencia e inicio da conexao com a ethernet */
    EthernetInterface eth;
    __init_eth__( &eth );
        
    /* debugs */
    debug_server.set_address( "192.168.120.144", 9897 );
    debug.bind( 72133 );
    debug.init();
    
    Timer t;
    Timer reboot;
    t.start();
          
    /* representa ramal do call box */
    int ext = 0;
    
    /* representa porta do call box */
    int port = 0; 
    
    /* buffer para onde se copia os dados vindos do cb para tratameno interno */
    uint8_t buffer[ __CB_BUFFER_SIZE__ ]; 
    
    /* buffer de escrita do pacote de saida que sera enviado pro cb / servidor */
    uint8_t write_buffer[ __CB_BUFFER_SIZE__ ];
    
    /* ponteiro que aponta para os dados vindo do CPLD */
    uint8_t * buffer_from_cb_ptr = ( uint8_t * )RXBuffer;
    
    /* referencia para os dados contidos no pacote, sem o header */
    uint8_t * data = NULL;
    
    /* gerencia o tipo do pacote para providenciar tratamento adequado */
    volatile uint8_t type = __DO_NOTHING__;
    
    /* representa a lista dos Call Boxes atualmente reconhecidos pela cabeceira */
    Vector * v_cb = new Vector();
    
    /* representa a lista de ligacoes ativas na cabeceira */
    Vector * v_call = new Vector();
    
    /* gerencia a distribuicao de timeslice para os call boxes */
    Timeslice * ts = new Timeslice();
    
    /* tenta instanciar o vetor de call boxes, acende o led 1 antes de encerrar o programa */
    reset_leds();
    if( v_cb == NULL ){
        led1 = 0;
        while( v_cb == NULL ){
            Vector * v_cb = new Vector();
            led1 = led1;
            if( t.read() > 5 ){
                debug_msg("Erro ao alocar o vetor de CBx");
                t.reset();
            }
        }
    }else if( v_call == NULL ){
        led2 = 0;
        led1 = 1;
        while( v_call == NULL ){
            Vector * v_call = new Vector();
            led1 = led1;
            if( t.read() > 5 ){
                debug_msg("Erro ao alocar o vetor de Calls");
                t.reset();
            }
        }
    }
    reset_leds();
    reboot.start();
    debug_msg( " Ready " );
    
    
    char test_buffer[400];
    UDPSocket test_sock;
    Endpoint test_server;
    test_server.set_address( "192.168.120.144" , 12345 );
    test_sock.set_blocking( false, 1 ); 
    test_sock.bind( 78965 );
    test_sock.init();
    int n = 0;
    strcpy( test_buffer, "a");
    test_sock.sendTo( test_server, test_buffer, sizeof( test_buffer ) );
    Timer reconnect;
    reconnect.start();
    
    while( true ){
        
        n  = test_sock.receiveFrom( test_server, test_buffer, sizeof( test_buffer ) );
        if( n > 0 ){
            test_sock.sendTo( test_server, test_buffer, n );
            reconnect.reset();
        }else if( reconnect.read() > 1 ){
            test_sock.close();
            test_sock.bind( 78965 );
            test_sock.init();
            reconnect.reset();
            test_sock.sendTo( test_server, test_buffer, n );
            led4 = !led4;
        }
    
        if( status != __WAITING__ ){
            __read_cb_buffer__( buffer, buffer_from_cb_ptr );     
            status = __WAITING__;
        
            data = __parse_cb_buffer__( &ext, &port, &type, buffer );
            
            if( data != NULL ){
                
                if( type == __CB_BYE__ ){
                    debug_msg("--> %s <--", buffer);    
                }
                if( type != __AUDIO__ ){
                    Call_Box * cb = __find_CB__( v_cb, ext );
                    if( cb != NULL ){
                        if( ( data[ 0 ] ^ cb->get_msg_id() ) == BIT7 ){
                            // some pkg reply
                            if( ( data[ 0 ] | BIT7 ) == cb->get_msg_id() ){                        
                                if( type == __BOOT__ ) type = __REGISTRY__;
                                __send_to_cb__( __build_cb_package__( ext, port, type, 
                                ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                                type = __DO_NOTHING__;
                                debug_msg("-- Renviado ultimo pkg --");
                            }else if( data[ 0 ] == ( cb->get_msg_id() | BIT7 ) ){
                                // ack from CBx
                                type = __DO_NOTHING__;
                                debug_msg("-- ACK do meu pkg --");
                            }
                        }
                    }
                }
            }else type = __DO_NOTHING__;
            /*
            if( data == NULL ) type = __DO_NOTHING__;
            */
        }
//----------------------            
            if( t.read() > 5 ){            
                for( register uint8_t i = 0; i < v_cb->size(); i++ ){
                    Call_Box * cb = ( Call_Box * )v_cb->get_element( i );
                    debug_msg(" Type ::  %d -- Ext :: %d -- TimeSlice :: %d -- remain_timeslices :: %d :: v_call->size() :: %d :: Status :: %d :: SIP Status %d", type , cb->get_ext(), cb->get_timeslice(), ts->remain_timeslices(), v_call->size(), cb->status, cb->sip->status );
                }
                t.reset();
                led3 = !led3;
            }
            if( reboot.read() > 180 ){
                for( register uint8_t i = 0; i < v_cb->size(); i++ ){
                    Call_Box * cb = ( Call_Box * )v_cb->get_element( i );
                    cb->set_timeslice( 0x00 );
                    set_status(cb->status,cb_idle);
                    set_status( cb->sip->status, sip_idle );
                    debug_msg( "Erased >> Type ::  %d -- Ext :: %d -- TimeSlice :: %d -- remain_timeslices :: %d :: v_call->size() :: %d  :: Status :: %d", type , cb->get_ext(), cb->get_timeslice(), ts->remain_timeslices(), v_call->size(), cb->status );
                }
                for( register uint8_t i = 0; i < v_call->size(); i++ ){
                    VZ_call * call = ( VZ_call * )v_call->get_element( i );
                    v_call->remove_element( i );
                    delete( call );   
                }
                reboot.reset();
                led4 = !led4;
            }
//----------------------
        switch( type ){
            case __DO_NOTHING__ :{}
                break;
                
            case __CB_BYE__ : {
                Call_Box * cb = __find_CB__( v_cb, ext );
                if( cb != NULL ){
                    data[ 0 ] |= BIT7;
                    cb->set_msg_id( data[ 0 ] );
                    debug_msg( " Request bye from CBx " );
                    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 ){
                            ts->return_timeslice( cb->get_timeslice() );
                            cb->set_timeslice( 0x00 );
                            set_status( cb->status, cb_idle );
                            v_call->remove_element( i );
                            cb->send_bye();
                            set_status( cb->sip->status, sip_idle);
                            data[ __TIMESLICE_PLACE__ ] = 0x00;
                            __send_to_cb__( __build_cb_package__( ext, port, __CB_BYE__,
                                ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                            set_status( cb->sip->status, sip_idle );
                        }
                    }
                }
            }break;
            
            case __INVITE__ : {
                #ifndef on_work
                // invite de uma ligacao em andamento ?
                Call_Box * cb = __find_CB__( v_cb, ext );
                if( cb != NULL ){
                    cb->reset_elapsed_time();
                    if( cb->status == cb_on_call ){
                        VZ_call * vz = __find_Call__( v_call, cb->get_ext() );
                        if( vz != NULL ) break;
                        ts->return_timeslice( cb->get_timeslice() );
                        cb->set_timeslice( 0x00 );
                        set_status(cb->status,cb_idle);
                    }
                }else{
                    cb = new Call_Box( ext, port );
                    v_cb->add( cb );
                }
                if( cb->status != cb_on_call ) set_status(cb->status,cb_ringing);
                if( data[ __TIMESLICE_PLACE__ ] == __CB_BYE__ ){ 
                    if( cb->status == cb_on_call ){    
                        for( register uint8_t i = 0; i < v_call->size(); i++ ){
                            if( ( (VZ_call *)v_call->get_element( i ) )->get_cb_ext() == ext ){
                                v_call->remove_element( i );
                                ts->return_timeslice( cb->get_timeslice() );
                                cb->set_timeslice( 0x00 );
                                set_status(cb->status,cb_idle);
                                cb->send_bye();
                                break;
                            }
                        }
                    }
                }
                if( cb->status == cb_ringing ){
                    data[ 0 ] |= BIT7;
                    cb->set_msg_id( data[ 0 ] );
                    cb->set_timeslice( ts->get_timeslice() );
                    if( cb->get_timeslice() == 0x00 ){
                        set_status(cb->status,cb_idle);
                        data[ __CLOCK_SYNC_SIZE__ ] = 0x00;
                        __send_to_cb__( __build_cb_package__( ext, port, __INVITE__, 
                            ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                        break;
                    }
                    if( cb->status == cb_ringing ){
                        data[ __CLOCK_SYNC_SIZE__ ] = cb->get_timeslice();
                        __send_to_cb__( __build_cb_package__( ext, port, __INVITE__, 
                            ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                        
                        VZ_call * call = cb->invite();
                        
                        if( call != NULL ){
                            v_call->add( call );
                            set_status(cb->status,cb_on_call);
                            data[ __CLOCK_SYNC_SIZE__ ] = cb->get_timeslice();
                            __send_to_cb__( __build_cb_package__( ext, port, __INVITE__, 
                                ( char * )data, cb->get_msg_id()+1, __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                        }else{
                            set_status(cb->status,cb_idle);
                            ts->return_timeslice( cb->get_timeslice() );
                            data[ __CLOCK_SYNC_SIZE__ ] = 0x00;
                            __send_to_cb__( __build_cb_package__( ext, port, __INVITE__, 
                                ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                        }
                    }
                }
            }break;      
            #endif
            #ifdef on_work
                Call_Box * cb = __find_CB__( v_cb, ext );
                if( cb == NULL ){
                    cb = new Call_Box( ext, port );
                    v_cb->add( cb );
                    set_status( cb->status, cb_idle );
                    cb->registry();
                }
                cb->reset_elapsed_time();
                set_status( cb->status, cb_trying );
                debug_msg(" Ok temos um cbx encontrado com status :: %d", cb->status );
                switch( cb->status ){
                    case cb_on_call : {
                        // a priori, nao fazer nada
                        //data[ __TIMESLICE_PLACE__ ] = 0x00;
                        //__send_to_cb__( __build_cb_package__( ext, port, __BYE__, 
                        //    ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                    }break;
                    
                    case cb_ringing : {
                        // tratar sip 2
                    }break;
                
                    case cb_trying : {
                        data[ 0 ] |= BIT7;
                        cb->set_msg_id( data[ 0 ] );
                        cb->set_timeslice( ts->get_timeslice() );
                        if( cb->get_timeslice() == 0x00 ){
                            //sem timeslice pra tratar com o *
                            set_status(cb->status,cb_idle);
                            data[ __TIMESLICE_PLACE__ ] = 0x00;
                            __send_to_cb__( __build_cb_package__( ext, port, __INVITE__, 
                                ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                            set_status( cb->sip->status, sip_idle);
                            debug_msg( "-- Trying -- Sem TS -- %s ", write_buffer );
                        }else{
                            set_status(cb->status,cb_busy);
                            data[ __TIMESLICE_PLACE__ ] = cb->get_timeslice();
                            __send_to_cb__( __build_cb_package__( ext, port, __INVITE__, 
                                ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                            
                            debug_msg(" -- %d on %d -- ", cb->get_ext(), data[ __TIMESLICE_PLACE__ ] );
                             
                            cb->set_msg_id( ( ( cb->get_msg_id() ) + 1 ) & ( BIT7 ^ 0xff ) );     
                            VZ_call * call = cb->invite();
                        
                            if( call != NULL ){
                                v_call->add( call );
                                set_status(cb->status,cb_on_call);
                                
                                debug_msg(" -- %d on %d -- ", cb->get_ext(), data[ __TIMESLICE_PLACE__ ] );
                                __send_to_cb__( __build_cb_package__( ext, port, __INVITE__, 
                                    ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                                debug_msg( "-- Trying -- aceitando pedido de invite -- %s ", write_buffer );
                                //debug_pkg( 300, write_buffer );
                            }else{
                                set_status(cb->status,cb_idle);
                                ts->return_timeslice( cb->get_timeslice() );
                                cb->set_timeslice( 0x00 );
                                data[ __TIMESLICE_PLACE__ ] = 0x00;
                                debug_msg(" -- %d on %d -- ", cb->get_ext(), data[ __TIMESLICE_PLACE__ ] );
                                __send_to_cb__( __build_cb_package__( ext, port, __CB_BYE__, 
                                    ( char * )data, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                                debug_msg( "-- Trying -- Negando pedido de invite -- %s ", write_buffer );
                                set_status( cb->sip->status, sip_idle);
                            }
                        }
                    }break;
                    
                    case cb_busy : {
                        // tratar sip
                    }break;
                }                            
            }break;
            #endif
            case __REGISTRY__ :
              {
                Call_Box * cb;
                data[ 0 ] |= BIT7;
                cb = __find_CB__( v_cb, ext );
                if( cb != NULL ){
                    cb->reset_elapsed_time();
                }else{
                    cb = new Call_Box( ext, port );
                    v_cb->add( cb );
                }
                cb->registry();
              }break;
            case __BOOT__ :
                    __send_to_cb__( __build_cb_package__( ext, port, __REGISTRY__, 
                        ( char * )data, data[ 0 ], __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                    break;
            case __TELEMETRY__ :
                debug_msg("Leitura da bateria :: ( Id : %x, MSB : %x, LSB : %x )", data[ 0 ], data[ 1 ], data[ 2 ] );
                break;
            case __AUDIO__ : {
                Call_Box * cb;
                VZ_call * call = NULL;
                cb = NULL;
                call = __find_Call__( v_call, ext );
                if( call != NULL ){
                    //debug_( 240, data );
                    //debug_pkg( 242, data );
                    //char * pkg = call->build_eth_package( oitocentos );
                    //char * pkg = call->build_eth_package( data );
                    char * pkg = call->build_eth_package( data + 2 );
                    call->send_message( pkg );
                    cb = __find_CB__( v_cb, ext );
                    if( cb != NULL ) cb->reset_elapsed_time();
                }
            }break;
        }// fim switch
        for( register int i = 0; i < v_call->size(); i++ ){
            VZ_call * call = ( VZ_call * )v_call->get_element( i );
            int length = 0;
            char * tmp = call->get_eth_message( &length );
            if( tmp != NULL ){
                Call_Box * cb = NULL;
                int cb_port = 0xffff;
                cb = __find_CB__( v_cb, call->get_cb_ext() );
                if( cb != NULL ) cb_port = cb->get_port();                
                uint8_t * pkg2cb = __build_cb_package__( call->get_cb_ext(), cb_port, __AUDIO__, 
                    tmp, __AUDIO__, length, write_buffer );
                __send_to_cb__( pkg2cb );
            }
        } 
        //nessa funcao eu deveria me registar a cada 2 min por exemplo
        registry_aging( v_cb, data, write_buffer );
        int ret = sip_manager( v_cb, v_call, write_buffer );
        if( ret > 0x00 ){
            Call_Box * cb = __find_CB__( v_cb, ret );
            if( cb->status == cb_on_call ){
                ts->return_timeslice( cb->get_timeslice() );
                cb->set_timeslice( 0x00 );
                set_status(cb->status,cb_idle);
                buffer[ __TIMESLICE_PLACE__ ] = 0x00;
                cb->set_msg_id( ( ( cb->get_msg_id() ) + 1 ) & ( BIT7 ^ 0xff ) );
                for( register uint8_t i = 0; i < v_call->size(); i++ ){
                    VZ_call * call = ( VZ_call * )v_call->get_element( i );
                    v_call->remove_element( i );
                }
                __send_to_cb__( __build_cb_package__( ext, port, __CB_BYE__, 
                    ( char * )buffer, cb->get_msg_id(), __CB_BUFFER_SIZE__ - __VZ_HEADER_OFFSET__, write_buffer ) );
                set_status( cb->sip->status, sip_idle );
            }
        }
        call_manager( v_call, v_cb, data, write_buffer, ts );
        
        static uint8_t flag = 0;
        if( v_call->size() == 0 ){
            if (flag == 0) { flag = 1; }
            ts->reset();
        }else {
            if (flag == 1) { flag = 0; }
        }
        /* eu deveria tirar ts que nao constam em chamadas aqui */
        for( register uint8_t i = 0; i < v_cb->size(); i++ ){
            Call_Box * cb = ( Call_Box * )v_cb->get_element( i );
            if( cb->get_timeslice() != 0x00 ){
                VZ_call * call = __find_Call__( v_call, cb->get_ext() );
                if( call == NULL ){
                    ts->return_timeslice( cb->get_timeslice() );
                    cb->set_timeslice( 0x00 );
                    set_status(cb->status,cb_idle);
                }
            }
        }
        type = __DO_NOTHING__;
    }
}