root/vtcross/trunk/CR_shell/src/main_cognitive_radio.cpp @ 96

Revision 96, 15.2 KB (checked in by trnewman, 15 years ago)

Removed uneeded files.

Line 
1#include <iostream>
2#include <sys/types.h>
3#include <sys/wait.h>
4#include <sys/socket.h>
5#include <netinet/in.h>
6#include <netdb.h>
7#include "tinyxml.h"
8#include "tinystr.h"
9#include <arpa/inet.h>
10//#include "socket/ServerSocket.h"
11//#include "socket/SocketException.h"
12
13using namespace std;
14
15#define SERVER_PORT 30000
16
17struct CE_Info {
18        int numUtilities;
19        int numParameters;
20        int numObservables;
21};
22
23struct Utility {
24        string name;
25        string units;
26        string goal;
27        float target;
28    float value;
29};
30struct Affect {
31        Utility * u;
32        string relation;
33};
34struct Parameter {
35        string name;
36        string units;
37        float min;
38        int numAffects;
39        Affect affection_list[10];
40        float max;
41        float step;
42    float value;
43};
44
45struct Observable {
46        string name;
47        Affect affection_list[10];
48        int numAffects;
49    float value;
50};
51
52void print_current_config(Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info) {
53        int i = 0;
54        int j = 0;
55
56        for(i = 0; i < ce_info->numUtilities ; i++) {
57                cout << "Utility:  " << uList[i]->name << endl;
58                cout << "     Units:  " << uList[i]->units << endl;
59                cout << "     Goal:   " << uList[i]->goal << endl;
60                cout << "     Target: " << uList[i]->target << endl;
61        }
62
63        for(i = 0; i < ce_info->numParameters; i++) {
64                cout << "Parameter:  " << pList[i]->name << endl;
65        printf("Radio Operation Profile has been sucessfully sent.\n");
66                cout << "       Units:   " << pList[i]->units << endl;
67                cout << "       Min:     " << pList[i]->min << endl;
68                cout << "       Max:     " << pList[i]->max << endl;
69                cout << "       Step:    " << pList[i]->step << endl;
70                for(j = 0; j < pList[i]->numAffects; j++) {
71                        cout << "       Affect: " << pList[i]->affection_list[j].u->name << " -> " << pList[i]->affection_list[j].relation << endl;
72                }
73        }
74       
75    for(i = 0; i < ce_info->numObservables; i++) {
76                cout << "Observable:  " << oList[i]->name << endl;
77                for(j = 0; j < oList[i]->numAffects; j++) {
78                        cout << "       Affect: " << oList[i]->affection_list[j].u->name << " -> " << oList[i]->affection_list[j].relation << endl;
79                }
80        }
81}
82
83
84int parse_ce_config( TiXmlDocument * doc , Utility * u[], Parameter * p[], Observable * o[], CE_Info * ce_info) {
85
86        TiXmlElement* pElem;    //!current element
87        TiXmlElement* pChild;   //!current child of pElem
88        TiXmlElement* pChild1;  //!current child of pElem
89        TiXmlElement* pSecondChild;     //!current child of pElem
90        TiXmlHandle hDoc(doc);  //!handle to xml document
91        TiXmlHandle hRoot(0); //! handle to root element
92
93        int count = 0;
94        int i = 0;
95        int j = 0;
96        int k = 0;
97        int match_found = 0;
98
99        pElem = hDoc.FirstChildElement().Element();
100        if(!pElem) { cout << "no valid root! quit-ing function!" << endl; return 0; }
101        hRoot = TiXmlHandle(pElem);
102
103        // Pull utility information from XML file.
104
105        pElem = hRoot.FirstChild("utilities").Element();
106        pChild1 = hRoot.Child("utilities",count).Element();
107
108
109        for(pChild = pChild1->FirstChildElement("utility"); pChild; pChild = pChild->NextSiblingElement())
110        {
111                u[i] = new Utility;
112                const char *uName = pChild->Attribute("name");
113                if(uName) u[i]->name = uName;   
114                const char *uUnits = pChild->Attribute("units");
115                if(uUnits) u[i]->units = uUnits;
116                const char *uGoal = pChild->Attribute("goal");
117                if(uGoal) u[i]->goal = uGoal;
118                if(pChild->QueryFloatAttribute("target",&u[i]->target) != TIXML_SUCCESS) u[i]->target = -1;
119                i++;
120        }
121        ce_info->numUtilities = i;     
122        cout << "Initialize:: Parsed " << ce_info->numUtilities << " utilities." << endl;
123
124        // Pull observable information from XML file.
125        i = 0;
126        pElem = hRoot.FirstChild("observables").Element();
127        pChild1 = hRoot.Child("observables",count).Element();
128       
129        for(pChild = pChild1->FirstChildElement("observable"); pChild; pChild = pChild->NextSiblingElement())
130        {
131
132                const char *oName = pChild->Attribute("name");
133                o[i] = new Observable;
134
135                if(oName) o[i]->name = oName;
136               
137                j = 0;
138                for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; pSecondChild = pSecondChild->NextSiblingElement())
139                {
140                        const char *oUtilName = pSecondChild->Attribute("utility");
141
142                        // If a utility affects this parameter find the utility object and assign it
143                        if(oUtilName) {
144                                // Search for correct utility
145                                for( k=0 ; u[k]!=NULL ; k++ ){
146                                        if(u[k]->name == oUtilName) {
147                                                o[i]->affection_list[j].u = u[k];
148                                                // Set relationship
149                                                const char *oRelate = pSecondChild->Attribute("relationship");
150                                                if(oRelate) o[i]->affection_list[j].relation = oRelate;
151                                                j++;
152                                                match_found = 1;
153                                                break;
154                                        }
155                                }
156                        }
157                        if(!match_found) cout << "Error: " << o[i]->name << ": " << oUtilName << " not a valid utility: Affect not added." << endl;     
158                        match_found = 0;       
159                }
160                o[i]->numAffects = j;
161                i++;
162        }
163        ce_info->numObservables = i;   
164        cout << "Initialize:: Parsed " << ce_info->numObservables << " observables." << endl;
165       
166
167        // Pull parameter information from XML file.
168        pElem = hRoot.FirstChild("parameters").Element();
169        pChild1 = hRoot.Child("parameters",count).Element();
170       
171        i = 0;
172        for(pChild = pChild1->FirstChildElement("parameter"); pChild; pChild = pChild->NextSiblingElement())
173        {
174                p[i] = new Parameter;
175
176                const char *pName = pChild->Attribute("name");
177                if(pName) p[i]->name = pName;   
178                const char *pUnits = pChild->Attribute("units");
179                if(pUnits) p[i]->units = pUnits;
180
181                if(pChild->QueryFloatAttribute("min",&p[i]->min) != TIXML_SUCCESS) p[i]->min = -1;
182                if(pChild->QueryFloatAttribute("max",&p[i]->max) != TIXML_SUCCESS) p[i]->max = -1;
183                if(pChild->QueryFloatAttribute("step",&p[i]->step) != TIXML_SUCCESS) p[i]->step = -1;
184               
185                j = 0;
186                for(pSecondChild = pChild->FirstChildElement("affect"); pSecondChild; pSecondChild = pSecondChild->NextSiblingElement())
187                {
188                        const char *pUtilName = pSecondChild->Attribute("utility");
189                       
190                        // If a utility affects this parameter find the utility object and assign it
191                        if(pUtilName) {
192                                // Search for correct utility
193                                for( k=0 ; u[k]!=NULL ; k++ ){
194                                        if(u[k]->name == pUtilName) {
195                                                // If match found, assign it to this index
196                                                p[i]->affection_list[j].u = u[k];       
197                                                const char *pRelate = pSecondChild->Attribute("relationship");
198                                                if(pRelate) {
199                                                        p[i]->affection_list[j].relation = pRelate;
200                                                } else {
201                                                        cout << "Error: No relation found." << endl;
202                                                }
203                                                match_found = 1;
204                                                j++;
205                                                break;
206                                        }
207                                }
208                        }
209                        if(!match_found) cout << "Error: " << p[i]->name << ": " << pUtilName << " not a valid utility: Affect not added." << endl;     
210                        match_found = 0;       
211                }
212                p[i]->numAffects = j;
213                i++;
214
215        }
216        ce_info->numParameters = i;     
217        cout << "Initialize:: Parsed " << ce_info->numParameters << " parameters." << endl;
218        return 1;
219}
220
221
222void error(char *msg)
223{
224    perror(msg);
225    exit(1);
226}
227
228
229int ReceiveMessage(int socket,char * buffer)
230{
231    int i,n;
232   
233    n = recv(socket,buffer,256,MSG_PEEK);
234    for(i=0;i<256;i++){
235        if(strcmp(&buffer[i],"\0") == 0) break;
236    }
237    n = recv(socket,buffer,i+1,0);
238    if (n < 0)
239        error("ERROR reading from socket");
240    //    printf("ReadMessage:%s %d\n",buffer,n);
241
242    return n;
243}
244
245
246int SendMessage(int socketfd, string message) {
247        int n;
248
249        message.append("\0");   
250        // Write message back to client
251    n = write(socketfd,message.c_str(),(message.size()+1));
252    if (n<0)
253        error("Error sending to client\n");
254    if(n == 0)
255        printf("Client closed the socket.\n");
256
257        //printf("SendMessage:%s %d\n",message.c_str(),n);     
258    return n;
259}
260
261void GetEnvironment() {
262
263}
264
265void Policy_ValidateSettings() {
266
267}
268
269
270void LoadCEConfiguration(int socketfd,Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info){
271        int n,i,j;
272        char counter[55];
273        char var[50];
274        //int total_bytes;   
275
276        printf("Sending Radio Operating Profile to Cognitive Engine.\n\n");
277 
278        // utilities
279        // Send number of utilities
280        sprintf(counter,"%d",ce_info->numUtilities);
281        SendMessage(socketfd,counter);
282        // send utility
283    for(i = 0; i < ce_info->numUtilities; i++) {
284                SendMessage(socketfd,uList[i]->name);
285                SendMessage(socketfd,uList[i]->units);
286                SendMessage(socketfd,uList[i]->goal);
287                sprintf(var,"%f",uList[i]->target);
288                SendMessage(socketfd,var);
289        }
290
291        // parameters
292    sprintf(counter,"%i",ce_info->numParameters);
293        SendMessage(socketfd,counter);
294        for(i = 0; i < ce_info->numParameters; i++) {
295                SendMessage(socketfd,pList[i]->name);
296                SendMessage(socketfd,pList[i]->units);
297                sprintf(var,"%f",pList[i]->min);
298                SendMessage(socketfd,var);
299                sprintf(var,"%f",pList[i]->max);
300                SendMessage(socketfd,var);
301                sprintf(var,"%f",pList[i]->step);
302                SendMessage(socketfd,var);
303               
304                sprintf(counter,"%i",pList[i]->numAffects);
305                SendMessage(socketfd,counter);
306                for(j = 0; j < pList[i]->numAffects; j++) {
307                        SendMessage(socketfd,pList[i]->affection_list[j].u->name);
308                        SendMessage(socketfd,pList[i]->affection_list[j].relation);
309                }
310        }
311
312    // observables
313        sprintf(counter,"%i",ce_info->numObservables);
314        SendMessage(socketfd,counter);
315        for(i = 0; i < ce_info->numObservables; i++) {
316                SendMessage(socketfd,oList[i]->name);
317               
318                sprintf(counter,"%i",oList[i]->numAffects);
319                SendMessage(socketfd,counter);
320                for(j = 0; j < oList[i]->numAffects; j++) {
321                        SendMessage(socketfd,oList[i]->affection_list[j].u->name);
322                        SendMessage(socketfd,oList[i]->affection_list[j].relation);
323                }
324        }
325       
326        // Receive ACK for utils
327    char buffer[256];
328        string message;
329        n = ReceiveMessage(socketfd, buffer);
330    //printf("%s\n", buffer);
331        //cout << message << endl;
332        //printf("ACK received.\n");
333
334}
335
336void UpdateCEConfiguration() {
337
338}
339
340void ResetCEConfiguration(){
341
342}
343
344void UpdateCEExperience(int socketfd, int num_rows, int num_cols,
345        float * past_exp[])
346{
347    char buffer[256];
348    int i, j;
349        char counter[55];
350        char var[50];
351
352    for (i = 0; i < num_rows; i++){
353        for (j = 0; j< num_cols; j++){
354                sprintf(var,"%f",past_exp[i][j]);
355        //printf("%f, \n", past_exp[i][j]);
356        //printf("%s, \n", var);
357        }
358    }
359   
360    // send the number of rows to the ce first
361        sprintf(counter,"%d",num_rows);
362        SendMessage(socketfd,counter);
363    // send the number of columns to the ce
364        sprintf(counter,"%d",num_cols);
365        SendMessage(socketfd,counter);
366    // update ce with experience
367    for (i = 0; i < num_rows; i++){
368        for (j = 0; j< num_cols; j++){
369                sprintf(var,"%f",past_exp[i][j]);
370                SendMessage(socketfd,var);
371        }
372    }
373
374}
375
376void ResetCEExperience() {
377
378}
379
380// Update operating settings
381// This function will interact with the hardware "drivers"
382void UpdateRadioSettings()
383{
384}
385
386int RequestCEOptimization(int sockfd, Utility *uList[],
387        Parameter *pList[], Observable *oList[],
388        CE_Info *ce_info)
389{
390    char buffer[256];
391    int i;
392    float var;
393
394    // Send request optimization message followed by the current environment parameters.
395    /*
396    SendMessage(sockfd,"request");
397    for (i = 0; i < ce_info->numObservables; i++){
398        SendMessage(sockfd,..);
399    }
400    */
401
402    // Receive optimized values from the Cognitive Engine
403    for (i = 0; i < ce_info->numParameters; i++){
404        bzero(buffer,256);
405        ReceiveMessage(sockfd,buffer);
406        var = atof(buffer);
407        pList[i]->value = var;
408    }
409
410
411    return 1;
412}
413
414void RunSimulator(int socketfd, Utility * uList[],
415        Parameter * pList[], Observable * oList[],
416        CE_Info * ce_info) {
417       
418        float **past_exp;
419    int num_rows, num_cols;
420
421        // Set fake current environment params = current environment
422        RequestCEOptimization(socketfd, uList, pList, oList, ce_info);
423
424        // Act like we are updating the hardware tranmission settings
425        UpdateRadioSettings();
426
427        // Send back fake utility values
428    // need to initialize
429        //UpdateCEExperience(socketfd, num_rows, num_cols, past_exp);   
430}
431
432void StartMessaging(int socketfd, Utility * uList[], Parameter * pList[], Observable * oList[], CE_Info * ce_info)
433{
434        LoadCEConfiguration(socketfd, uList, pList, oList, ce_info);
435       
436    // cr experience
437    float **past_exp;
438        int num_cols;
439    // get number of columns
440    num_cols = ce_info->numUtilities + ce_info->numParameters;
441    num_cols = num_cols + ce_info->numObservables;
442    num_cols = num_cols + 1;    // overall utility
443    int num_rows = 2;
444    past_exp = (float **)malloc(sizeof(float)*num_rows);
445    int i;
446    for (i=0; i<num_rows; i++){
447        past_exp[i] = (float*)malloc(sizeof(float)*num_cols);
448    }
449    // sample experience #1
450    past_exp[0][0] = 1e3f;  // throughput
451    past_exp[0][1] = 1;     // spectral_efficiency
452    past_exp[0][2] = -3.5;  // log10_ber
453    past_exp[0][3] = 1;     // mod_scheme
454    past_exp[0][4] = -10;   // tx_power
455    past_exp[0][5] = 10.0;  // SNR
456    past_exp[0][6] = 0.762; // overall utility*/
457    // sample experience #2
458    past_exp[1][0] = 1e2f;  // throughput
459    past_exp[1][1] = 1;     // spectral_efficiency
460    past_exp[1][2] = -3.5;  // log10_ber
461    past_exp[1][3] = 1;     // mod_scheme
462    past_exp[1][4] = -14;   // tx_power
463    past_exp[1][5] = 3.0;   // SNR
464    past_exp[1][6] = 0.462; // overall utility
465
466
467        // update ce with experience
468    printf("Sending Previous Experience to New Cognitive Engine.\n\n");
469    UpdateCEExperience(socketfd, num_rows, num_cols, past_exp);
470
471        RunSimulator(socketfd, uList, pList, oList, ce_info);
472}
473
474int 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        //}
507        return 0;
508}
509
510int main(int argc, char* argv[]) {
511
512
513        // CognitiveEngine CE;
514        // CognitiveEngineShell Shell;
515        string pFilename;
516        int pid;
517
518        Utility * uList[10];
519        Parameter * pList[10];
520        Observable * oList[10];
521        CE_Info ce_info;
522
523        if(argc < 2) {
524                cout << "Warning no XML file specific using default: example.xml" << endl;
525                pFilename = "example.xml";
526        } else { 
527                pFilename = argv[1];
528        }
529
530        TiXmlDocument doc( pFilename.c_str() );
531        bool loadOkay = doc.LoadFile();
532        if (!loadOkay)
533        {
534                cout << "Loading " << pFilename << " failed." << endl;
535                return 0;
536        }
537
538        cout << "\n\nInitialize:: Attemping to parse " << pFilename << "." << endl;
539        parse_ce_config( &doc , uList, pList, oList, &ce_info);
540        cout << "Initialize:: Configuration file parsing completed.\n" << endl;
541
542    //print_current_config(uList, pList, oList, &ce_info);
543       
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
554   return 1;
555}
Note: See TracBrowser for help on using the browser.