Changeset 97

Show
Ignore:
Timestamp:
02/16/09 16:54:59 (15 years ago)
Author:
anonymous
Message:

cleaning up code

Location:
vtcross/trunk/CR_shell/src
Files:
1 removed
1 modified

Legend:

Unmodified
Added
Removed
  • vtcross/trunk/CR_shell/src/main_cognitive_radio.cpp

    r96 r97  
    88#include "tinystr.h" 
    99#include <arpa/inet.h> 
     10#include <sys/mman.h> 
     11#include <fcntl.h> 
     12#include <sys/ioctl.h> 
     13 
    1014//#include "socket/ServerSocket.h" 
    1115//#include "socket/SocketException.h" 
     
    1317using namespace std; 
    1418 
    15 #define SERVER_PORT 30000 
     19#define CE_SERVER_PORT 30001 
     20#define POLICY_SERVER_PORT 30003 
    1621 
    1722struct CE_Info { 
     
    1924        int numParameters; 
    2025        int numObservables; 
     26    int policy_engine; 
     27    int policy_socket; 
     28    int ce_socket; 
    2129}; 
    2230 
     
    5058}; 
    5159 
     60void DieWithError(char *errorMessage) 
     61{ 
     62        perror(errorMessage); 
     63            exit(1); 
     64} 
     65 
    5266void print_current_config(Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) { 
    5367        int i = 0; 
     
    6377        for(i = 0; i < ce_info->numParameters; i++) { 
    6478                cout << "Parameter:  " << pList[i]->name << endl; 
    65         printf("Radio Operation Profile has been sucessfully sent.\n"); 
     79        printf("Cognitive Radio:: Radio Operation Profile has been sucessfully sent.\n"); 
    6680                cout << "       Units:   " << pList[i]->units << endl; 
    6781                cout << "       Min:     " << pList[i]->min << endl; 
     
    230244{ 
    231245    int i,n; 
    232      
     246    
    233247    n = recv(socket,buffer,256,MSG_PEEK); 
     248     
    234249    for(i=0;i<256;i++){ 
    235250        if(strcmp(&buffer[i],"\0") == 0) break; 
     
    249264        message.append("\0");    
    250265        // Write message back to client 
    251     n = write(socketfd,message.c_str(),(message.size()+1)); 
     266    n = send(socketfd,message.c_str(),(message.size()+1),0); 
    252267    if (n<0) 
    253268        error("Error sending to client\n"); 
     
    274289        //int total_bytes;    
    275290 
    276         printf("Sending Radio Operating Profile to Cognitive Engine.\n\n"); 
     291        printf("Cognitive Radio:: Sending Radio Operating Profile to Cognitive Engine.\n\n"); 
    277292  
    278293        // utilities 
     
    345360        float * past_exp[])  
    346361{ 
    347     char buffer[256]; 
    348362    int i, j; 
    349363        char counter[55]; 
     
    384398} 
    385399 
     400 
     401int RequestPolicyValidation(Parameter * pList[], CE_Info *ce_info) 
     402{ 
     403        char counter[55]; 
     404        char var[50]; 
     405    int i; 
     406    string control_msg; 
     407     
     408    int socketfd = ce_info->policy_socket; 
     409 
     410    // Control message that validation request is coming 
     411    control_msg = "val"; 
     412        SendMessage(socketfd,control_msg); 
     413 
     414    printf("Cognitive Radio:: Here. %i\n\n", socketfd); 
     415 
     416        // Send parameter information  
     417    sprintf(counter,"%i",ce_info->numParameters); 
     418        SendMessage(socketfd,counter); 
     419        for(i = 0; i < ce_info->numParameters; i++) { 
     420                SendMessage(socketfd,pList[i]->name); 
     421                SendMessage(socketfd,pList[i]->units); 
     422                sprintf(var,"%f",pList[i]->min); 
     423                SendMessage(socketfd,var); 
     424                sprintf(var,"%f",pList[i]->max); 
     425                SendMessage(socketfd,var); 
     426                sprintf(var,"%f",pList[i]->step); 
     427                SendMessage(socketfd,var); 
     428                sprintf(var,"%f",pList[i]->value); 
     429                SendMessage(socketfd,var); 
     430                 
     431        } 
     432    return 1; 
     433 
     434} 
     435 
     436 
    386437int RequestCEOptimization(int sockfd, Utility *uList[],  
    387438        Parameter *pList[], Observable *oList[], 
     
    409460 
    410461 
     462    // If policy engine is connect, validate new values 
     463    if(ce_info->policy_engine == 1) { 
     464 
     465        printf("Cognitive Radio:: Found Policy Engine!\n"); 
     466        printf("Cognitive Radio:: Validating parameters with Policy Engine\n\n"); 
     467        RequestPolicyValidation(pList,ce_info);  
     468        printf("Cognitive Radio:: Done\n\n"); 
     469 
     470    } 
     471 
     472 
    411473    return 1; 
    412474} 
     
    430492} 
    431493 
    432 void StartMessaging(int socketfd, Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info)  
     494void InitializePE(int socket, CE_Info * ce_info)  
     495{ 
     496    // Policy Engine is connected 
     497    // Set global policy engine value to 1 
     498    ce_info->policy_engine = 1; 
     499    ce_info->policy_socket = socket; 
     500 
     501    return; 
     502} 
     503 
     504void InitializeCE(int socketfd, Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info)  
    433505{ 
    434506        LoadCEConfiguration(socketfd, uList, pList, oList, ce_info); 
     
    464536    past_exp[1][6] = 0.462; // overall utility 
    465537 
    466  
    467538        // update ce with experience 
    468     printf("Sending Previous Experience to New Cognitive Engine.\n\n"); 
     539    printf("Cognitive Radio:: Sending Previous Experience to New Cognitive Engine.\n\n"); 
    469540    UpdateCEExperience(socketfd, num_rows, num_cols, past_exp);  
    470541 
     
    472543} 
    473544 
    474 int StartShell(int port,Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) { 
    475         // Start socket server 
    476         int sockfd, newsockfd, clilen; 
    477         struct sockaddr_in serv_addr, cli_addr; 
    478         char str[20]; 
    479  
    480         // Setup server socket connection 
    481         sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    482         if (sockfd < 0)  
    483                 error("ERROR opening socket"); 
    484         bzero((char *) &serv_addr, sizeof(serv_addr)); 
    485         serv_addr.sin_family = AF_INET; 
    486         serv_addr.sin_port = htons(port); 
    487         serv_addr.sin_addr.s_addr = INADDR_ANY; 
    488         if (bind(sockfd, (struct sockaddr *) &serv_addr, 
    489                 sizeof(serv_addr)) < 0)  
    490                 error("ERROR on binding"); 
    491         listen(sockfd,5); 
    492         clilen = sizeof(cli_addr); 
    493  
    494         //while(1) { 
    495                 newsockfd = accept(sockfd,  
    496                         (struct sockaddr *) &cli_addr,  
    497                         (socklen_t*)&clilen); 
    498                 if (newsockfd < 0)  
    499                         error("ERROR on accept"); 
    500  
    501         inet_ntop(AF_INET,&(cli_addr.sin_addr),str,20);  
    502         printf("Received a connection from a Cognitive Engine with IP address: %s\n\n",str); 
    503  
    504                 // Begin parsing the messages 
    505                 StartMessaging(newsockfd, uList, pList, oList, ce_info); 
    506         //} 
     545int AcceptTCPConnection(int servSock) 
     546{ 
     547    int clntSock;                    /* Socket descriptor for client */ 
     548    struct sockaddr_in echoClntAddr; 
     549    unsigned int clntLen; 
     550 
     551    /* Set the size of the in-out parameter */ 
     552    clntLen = sizeof(echoClntAddr); 
     553 
     554    /* Wait for a client to connect */ 
     555    //if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, &clntLen)) < 0) { 
     556    if ((clntSock = accept(servSock, NULL, NULL)) < 0) { 
     557        return -1; 
     558    }  
     559    
     560    /* clntSock is connected to a client! */ 
     561     
     562    printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr)); 
     563 
     564    return clntSock; 
     565} 
     566 
     567int CreateTCPServerSocket(unsigned short port) 
     568{ 
     569    int sock;                        /* socket to create */ 
     570    struct sockaddr_in echoServAddr; /* Local address */ 
     571 
     572    /* Create socket for incoming connections */ 
     573    if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) 
     574        DieWithError("socket() failed"); 
     575       
     576    /* Construct local address structure */ 
     577    memset(&echoServAddr, 0, sizeof(echoServAddr));   /* Zero out structure */ 
     578    echoServAddr.sin_family = AF_INET;                /* Internet address family */ 
     579    echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */ 
     580    echoServAddr.sin_port = htons(port);              /* Local port */ 
     581 
     582    /* Bind to the local address */ 
     583    if (bind(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0) 
     584        DieWithError("bind() failed"); 
     585 
     586    /* Mark the socket so it will listen for incoming connections */ 
     587    if (listen(sock, 5) < 0) { 
     588        printf("listen() failed\n"); 
     589        return 0; 
     590    } 
     591 
     592    return sock; 
     593} 
     594 
     595void HandleTCPClient(int socketfd, Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info)  
     596{ 
     597    char buffer[256];        /* Buffer for echo string */ 
     598 
     599    /* Receive message from client */ 
     600    bzero(buffer,256); 
     601    ReceiveMessage(socketfd,buffer); 
     602 
     603    printf("Cognitive Radio:: Message Received - %s.\n\n", buffer); 
     604 
     605    if(strcmp(buffer,"c_register") == 0)  
     606            InitializeCE(socketfd, uList, pList, oList, ce_info); 
     607 
     608    if(strcmp(buffer,"p_register") == 0) 
     609            InitializePE(socketfd, ce_info); 
     610 
     611    if(strcmp(buffer,"optimize") == 0) 
     612            RunSimulator(socketfd, uList, pList, oList, ce_info); 
     613         
     614    //close(socketfd);    /* Close client socket */ 
     615} 
     616 
     617int StartServers(Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) { 
     618    int * servSock;  
     619    int running = 1; 
     620    struct timeval selTimeout; 
     621    int timeout = 10; 
     622    int cognitive_engine = 0;  
     623    int policy_engine = 1;  
     624    int port, rc, on = 1; 
     625    int new_sd; 
     626    int desc_ready = 0; 
     627    fd_set sockSet; 
     628     
     629    servSock = (int *) malloc(2 * sizeof(int)); 
     630 
     631    servSock[cognitive_engine] = CreateTCPServerSocket(CE_SERVER_PORT); 
     632    servSock[policy_engine] = CreateTCPServerSocket(POLICY_SERVER_PORT); 
     633 
     634 
     635    int maxDescriptor = servSock[cognitive_engine]; 
     636 
     637    if(servSock[cognitive_engine] < servSock[policy_engine]) 
     638        maxDescriptor = servSock[policy_engine]; 
     639 
     640    rc = setsockopt(servSock[cognitive_engine], SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)); 
     641    if(rc < 0) 
     642    { 
     643        perror("setsockopt() failed"); 
     644        close(servSock[cognitive_engine]); 
     645        exit(-1); 
     646    } 
     647     
     648    rc = setsockopt(servSock[policy_engine], SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)); 
     649    if(rc < 0) 
     650    { 
     651        perror("setsockopt() failed"); 
     652        close(servSock[policy_engine]); 
     653        exit(-1); 
     654    } 
     655     
     656    rc = ioctl(servSock[cognitive_engine], FIONBIO, (char*)&on); 
     657    if(rc < 0) 
     658    { 
     659        perror("ioctl() failed"); 
     660        close(servSock[cognitive_engine]); 
     661        exit(-1); 
     662    } 
     663     
     664    rc = ioctl(servSock[policy_engine], FIONBIO, (char*)&on); 
     665    if(rc < 0) 
     666    { 
     667        perror("ioctl() failed"); 
     668        close(servSock[policy_engine]); 
     669        exit(-1); 
     670    } 
     671     
     672    printf("Starting server:  Hit return to shutdown\n"); 
     673    while (running) 
     674    { 
     675        /* Zero socket descriptor vector and set for server sockets */ 
     676        /* This must be reset every time select() is called */ 
     677        FD_ZERO(&sockSet); 
     678        /* Add keyboard to descriptor vector */ 
     679        FD_SET(STDIN_FILENO, &sockSet); 
     680        FD_SET(servSock[cognitive_engine], &sockSet); 
     681        FD_SET(servSock[policy_engine], &sockSet); 
     682 
     683        /* Timeout specification */ 
     684        /* This must be reset every time select() is called */ 
     685        selTimeout.tv_sec = timeout;       /* timeout (secs.) */ 
     686        selTimeout.tv_usec = 0;            /* 0 microseconds */ 
     687 
     688        /* Suspend program until descriptor is ready or timeout */ 
     689        rc = select(maxDescriptor + 1, &sockSet, NULL, NULL, &selTimeout);  
     690        if (rc == 0) 
     691            printf("No echo requests for %i secs...Server still alive\n", timeout); 
     692        else  
     693        { 
     694            if (FD_ISSET(0, &sockSet)) /* Check keyboard */ 
     695            { 
     696                printf("Shutting down server\n"); 
     697                getchar(); 
     698                running = 0; 
     699            } 
     700 
     701            desc_ready = rc; 
     702 
     703            for (port = 0; port <= maxDescriptor && desc_ready > 0; port++) { 
     704                if (FD_ISSET(port, &sockSet)) 
     705                { 
     706                    printf("Request on port %d:  ", port); 
     707                        desc_ready -= 1; 
     708 
     709 
     710                    if( (port == servSock[cognitive_engine]) || (port == servSock[policy_engine])) {  
     711                        
     712                        do 
     713                        {  
     714                            new_sd = AcceptTCPConnection(port); 
     715                            if(new_sd < 0)  
     716                            { 
     717                                break; 
     718                            } 
     719                             
     720                            HandleTCPClient(new_sd, uList, pList, oList, ce_info); 
     721                            FD_SET(new_sd,&sockSet); 
     722                            if(new_sd > maxDescriptor)  
     723                                maxDescriptor = new_sd; 
     724                            printf("New incoming connection - %i\n\n",new_sd); 
     725                        } while(new_sd != -1); 
     726                    } else { 
     727                         
     728                        printf("Request on already open descriptor.\n\n"); 
     729                        HandleTCPClient(port, uList, pList, oList, ce_info); 
     730 
     731                    } 
     732 
     733                } 
     734            } 
     735        } 
     736    } 
     737 
     738    /* Close sockets */ 
     739    for (port = 0; port < 2; port++) 
     740        close(servSock[port]); 
     741 
     742    /* Free list of sockets */ 
     743    free(servSock);         
     744         
    507745        return 0; 
    508746} 
     
    514752        // CognitiveEngineShell Shell; 
    515753        string pFilename;  
    516         int pid; 
     754    int fd; 
    517755 
    518756        Utility * uList[10]; 
    519757        Parameter * pList[10]; 
    520758        Observable * oList[10]; 
    521         CE_Info ce_info; 
     759        struct CE_Info *ce_info; 
     760 
     761    if((fd = open("/dev/zero", O_RDWR)) == -1) 
     762            return 1; 
     763 
     764    ce_info = (struct CE_Info *)mmap(0,sizeof(CE_Info),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); 
     765 
     766    close(fd); 
    522767 
    523768        if(argc < 2) {  
     
    537782 
    538783        cout << "\n\nInitialize:: Attemping to parse " << pFilename << "." << endl; 
    539         parse_ce_config( &doc , uList, pList, oList, &ce_info); 
     784        parse_ce_config( &doc , uList, pList, oList, ce_info); 
    540785        cout << "Initialize:: Configuration file parsing completed.\n" << endl; 
    541786 
    542787    //print_current_config(uList, pList, oList, &ce_info); 
    543788         
    544     pid = fork(); 
    545         if(pid == 0) { 
    546                 // In child process - open policy engine port. 
    547         //      StartShell(30000,uList, pList, oList, &ce_info); 
    548         } else { 
    549                 // In parent process - open cognitive engine port. 
    550                 StartShell(30001,uList, pList, oList, &ce_info); 
    551         }  
    552          
    553  
     789   StartServers(uList, pList, oList, ce_info); 
    554790   return 1; 
    555791}