root/vtcross/trunk/src/service_management_layer/ServiceManagementLayer.cpp @ 292

Revision 292, 67.2 KB (checked in by wrodgers, 15 years ago)

Added non-observ/param inputs for missions

Line 
1/* Virginia Tech Cognitive Radio Open Source Systems
2 * Virginia Tech, 2009
3 *
4 * LICENSE INFORMATION GOES HERE
5 */
6
7/* Inter-component communication handled by sockets and FD's. 
8 * Server support has been completely implemented and tested.
9 *
10 * Services are stored in a SQLite DB by the ID of the CE that registered them.  Service
11 * support has been completely implemented and tested.
12 *
13 * Missions are loaded from an XML file, connected with services provided by components,
14 * and run.  See the documentation for the "PerformActiveMission" below for important
15 * info. 
16 */
17
18//TODO Add nested conditional support
19//TODO Verify update functionality
20//TODO Better shutdown
21//TODO Verify Deregister services
22//TODO printf's
23
24#include <stdlib.h>
25#include <string.h>
26#include <stdio.h>
27#include <cstring>
28#include <stdint.h>
29
30#include "vtcross/common.h"
31
32#include "components.h"
33#include "vtcross/containers.h"
34#include "vtcross/debug.h"
35#include "vtcross/error.h"
36#include "vtcross/socketcomm.h"
37#include <cstring>
38#include <stdint.h>
39#include <math.h>
40
41#include <arpa/inet.h>
42#include <iostream>
43#include <netinet/in.h>
44#include <netdb.h>
45#include <fcntl.h>
46#include <sys/ioctl.h>
47#include <sys/mman.h>
48#include <sys/socket.h>
49#include <sys/types.h>
50#include <sys/wait.h>
51
52#include "tinyxml/tinyxml.h"
53#include "tinyxml/tinystr.h"
54
55#include "sqlite3.h"
56
57typedef struct services_s *services_DB;
58typedef struct data_s *data_DB;
59
60using namespace std;
61
62struct services_s {
63    char filename[64];
64    char tablename[64];
65    char command[2048];
66    sqlite3 *db;
67    unsigned int num_columns;
68};
69
70struct data_s {
71    char filename[64];
72    char tablename[64];
73    char command[2048];
74    sqlite3 *db;
75    unsigned int num_columns;
76};
77
78services_DB _services_DB;
79data_DB _data_DB;
80const char *_SML_Config;
81
82//Callback function used internally by some of the SQLite3 commands
83int callback(void *notUsed, int argc, char **argv, char **azColName){
84    int i;
85    for(i=0; i<argc; i++){
86        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
87    }
88    printf("\n");
89    return 0;
90}
91
92
93
94ServiceManagementLayer::ServiceManagementLayer()
95{
96    LOG("Creating Service Management Layer.\n");
97    shellSocketFD = -1;
98    numberOfCognitiveEngines = 0;
99    CE_Present = false;
100    cogEngSrv = 1;
101}
102
103//Free and clear the DB's associated with this SML in the destructor
104//Note that exiting with an error condition will cause SML to not be destructed,
105// resulting in the DB's staying in memory until the destructor is encountered in future executions
106ServiceManagementLayer::~ServiceManagementLayer()
107{
108    char *errorMsg;
109    strcpy(_services_DB->command, "drop table ");
110    strcat(_services_DB->command, _services_DB->tablename);
111    int rc = sqlite3_exec(_services_DB->db, _services_DB->command, callback, 0, &errorMsg);
112    if( rc!=SQLITE_OK && rc!=101 )
113        fprintf(stderr, "ServiceManagementLayer::Destructor services 'drop table' error: %s\n", errorMsg);
114    strcpy(_services_DB->command, "vacuum");
115    rc = sqlite3_exec(_services_DB->db, _services_DB->command, callback, 0, &errorMsg);
116    if( rc!=SQLITE_OK && rc!=101 )
117        fprintf(stderr, "ServiceManagementLayer::Destructor services 'vacuum' error: %s\n", errorMsg);
118    free(_services_DB);
119
120    strcpy(_data_DB->command, "drop table ");
121    strcat(_data_DB->command, _data_DB->tablename);
122    rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
123    if( rc!=SQLITE_OK && rc!=101 )
124        fprintf(stderr, "ServiceManagementLayer::Destructor data 'drop table' error: %s\n", errorMsg);
125    strcpy(_data_DB->command, "vacuum");
126    rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
127    if( rc!=SQLITE_OK && rc!=101 )
128        fprintf(stderr, "ServiceManagementLayer::Destructor data 'vacuum' error: %s\n", errorMsg);
129    free(_data_DB);
130}
131
132//Note that sizes of CE_List, miss, and service are hardcoded for now.
133//Also, their sizes are hardcoded into the code in various places; a fix for a future version.
134ServiceManagementLayer::ServiceManagementLayer(const char* SML_Config, \
135        const char* serverName, const char* serverPort, int16_t clientPort)
136{
137    LOG("Creating Service Management Layer.\n");
138    _SML_Config = SML_Config;
139    SMLport = clientPort;
140
141    ConnectToShell(serverName, serverPort);
142    CE_List = (CE_Reg *) malloc(10*sizeof(struct CE_Reg));
143    CE_List = new CE_Reg[10];
144
145    miss = new Mission[10];
146    for(int i = 0; i < 10; i++)
147        miss[i].services = new Service[20];
148
149    Current_ID = 0;
150
151    LoadConfiguration(SML_Config, miss);
152    CreateServicesDB();
153    CreateDataDB();
154}
155
156/* CALLED BY: constructor
157 * INPUTS: <none>
158 * OUTPUTS: <none>
159 *
160 * DESCRIPTION: Create and initialize a DB to hold the services registered by components
161 */
162void
163ServiceManagementLayer::CreateServicesDB()
164{
165
166
167  sqlite3_stmt *ppStmt;  /* OUT: Statement handle */
168  const char *pzTail;     /* OUT: Pointer to unused portion of zSql */
169
170
171    _services_DB = (services_DB) malloc(sizeof(struct services_s));
172   // char *errorMsg;
173
174    // create database
175
176    // copy filename
177    strcpy(_services_DB->filename, "Services_Table");
178
179    // execute create database command
180    // database handle
181    //_services_DB->db = NULL;
182    sqlite3_open(_services_DB->filename, &(_services_DB->db));
183    char* cols[] = {(char *)"ID_Num", (char *)"Service_Name"};
184
185    // create table
186
187    // copy tablename
188    strcpy(_services_DB->tablename, "Services");
189    sprintf(_services_DB->command, "DROP TABLE IF EXISTS Services;");     
190
191    int rc = sqlite3_prepare_v2(_services_DB->db, _services_DB->command, 128, &ppStmt, &pzTail);
192    if( rc!=SQLITE_OK && rc!=101 )
193        printf("ServiceManagementLayer::CreateServicesDB 'prepare_stmt' error %d\n", rc);
194    rc = sqlite3_step(ppStmt);
195    if( rc!=SQLITE_OK && rc!=101 )
196        printf("ServiceManagementLayer::CreateServicesDB 'step' error\n");
197
198    // number of columns in the table
199    _services_DB->num_columns = 2;
200
201    // generate command
202    strcpy(_services_DB->command, "CREATE TABLE ");
203    strcat(_services_DB->command, _services_DB->tablename);
204    strcat(_services_DB->command, "(");
205    strcat(_services_DB->command, cols[0]);
206    strcat(_services_DB->command, " INT, ");
207    strcat(_services_DB->command, cols[1]);
208    strcat(_services_DB->command, " TEXT");
209    strcat(_services_DB->command, ");");
210
211    // execute create table command
212
213    rc = sqlite3_prepare_v2(_services_DB->db, _services_DB->command, 128, &ppStmt, &pzTail);
214    if( rc!=SQLITE_OK && rc!=101 )
215        printf("ServiceManagementLayer::CreateServicesDB 'prepare_stmt' error %d\n", rc);
216    rc = sqlite3_step(ppStmt);
217    if( rc!=SQLITE_OK && rc!=101 )
218        printf("ServiceManagementLayer::CreateServicesDB 'step' error\n");
219}
220
221/* CALLED BY: constructor
222 * INPUTS: <none>
223 * OUTPUTS: <none>
224 *
225 * DESCRIPTION: Create and initialize a DB to hold the data sent by components
226 */
227void
228ServiceManagementLayer::CreateDataDB()
229{
230    _data_DB = (data_DB) malloc(sizeof(struct data_s));
231    //char *errorMsg;
232  sqlite3_stmt *ppStmt;  /* OUT: Statement handle */
233  const char *pzTail;     /* OUT: Pointer to unused portion of zSql */
234
235    // create database
236
237    // copy filename
238    strcpy(_data_DB->filename, "Data_Table");
239    // execute create database command
240    // database handle
241    //_services_DB->db = NULL;
242    sqlite3_open(_data_DB->filename, &(_data_DB->db));
243    char* cols[] = {(char *)"Tag", (char *)"Data"};
244
245    // create table
246
247    // copy tablename
248    strcpy(_data_DB->tablename, "Data");
249    sprintf(_data_DB->command, "DROP TABLE IF EXISTS Data;");     
250
251    int rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, 128, &ppStmt, &pzTail);
252    if( rc!=SQLITE_OK && rc!=101 )
253        printf("ServiceManagementLayer::CreateServicesDB 'prepare_stmt' error %d\n", rc);
254    rc = sqlite3_step(ppStmt);
255    if( rc!=SQLITE_OK && rc!=101 )
256        printf("ServiceManagementLayer::CreateServicesDB 'step' error\n");
257
258
259    // number of columns in the table
260    _data_DB->num_columns = 2;
261
262    // generate command
263    strcpy(_data_DB->command, "CREATE TABLE ");
264    strcat(_data_DB->command, _data_DB->tablename);
265    strcat(_data_DB->command, "(");
266    strcat(_data_DB->command, cols[0]);
267    //First column is the name of the data (coresponding to the name of the output/input pair)
268    //It is the primary key so any subsequent data with the same name will replace the row
269    strcat(_data_DB->command, " TEXT PRIMARY KEY ON CONFLICT REPLACE, ");
270    strcat(_data_DB->command, cols[1]);
271    strcat(_data_DB->command, " TEXT");
272    strcat(_data_DB->command, ");");
273
274    // execute create table command
275
276    rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, 128, &ppStmt, &pzTail);
277    if( rc!=SQLITE_OK && rc!=101 )
278        printf("ServiceManagementLayer::CreateDataDB 'prepare_stmt' error %d\n", rc);
279    rc = sqlite3_step(ppStmt);
280    if( rc!=SQLITE_OK && rc!=101 )
281        printf("ServiceManagementLayer::CreateDataDB 'step' error\n");
282}
283
284/* CALLED BY: MessageHandler
285 * INPUTS: <none>
286 * OUTPUTS: <none>
287 *
288 * DESCRIPTION: Sends a message identifying this component as an SML to the Shell
289 */
290void
291ServiceManagementLayer::SendComponentType()
292{
293    SendMessage(shellSocketFD, "response_sml");
294    LOG("SML responded to GetRemoteComponentType query.\n");
295}
296
297/* CALLED BY: constructor
298 * INPUTS: |serverName| the IPv4 name of the server (127.0.0.1 for localhost)
299 *         |serverPort| the port on the server to connect to
300 * OUTPUTS: <none>
301 *
302 * DESCRIPTION: Connecting to the shell takes 2 steps
303 * 1) Establish a client socket for communication
304 * 2) Run the initial Registration/handshake routine
305 */
306void
307ServiceManagementLayer::ConnectToShell(const char* serverName, \
308        const char* serverPort)
309{
310    shellSocketFD = ClientSocket(serverName, serverPort);
311    RegisterComponent();
312}
313
314/* CALLED BY: StartSMLServer
315 * INPUTS: |ID| The ID number of the CE that has a message wating
316 * OUTPUTS: <none>
317 *
318 * DESCRIPTION: Called whenever a socket is identified as being ready for communication
319 *              This funciton reads the message and calls the appropriate helper
320 */
321void
322ServiceManagementLayer::MessageHandler(int32_t ID)
323{
324    char buffer[256];   
325    memset(buffer, 0, 256); 
326    int32_t _FD; 
327   
328    if(ID != -1)
329        _FD = CE_List[ID].FD;
330    else
331        _FD = shellSocketFD;
332    ReadMessage(_FD, buffer);
333    //printf("MH_buffer = %s\n", buffer);
334   
335    //--------Policy Engine Stuff - no policy engine support in this version-------//
336
337    //printf("********* %s **********\n", buffer);
338    // TODO
339    // If we send integer op codes rather than strings, this process will be
340    // MUCH faster since instead of donig string compares we can simply
341    // switch on the integer value...
342    /*if(strcmp(buffer, "register_service") == 0) {
343        if(strcmp(buffer, "policy_geo") == 0) {
344        }
345        else if(strcmp(buffer, "policy_time") == 0) {
346        }
347        else if(strcmp(buffer, "policy_spectrum") == 0) {
348        }
349        else if(strcmp(buffer, "policy_spacial") == 0) {
350        }
351    }
352    else if(strcmp(buffer, "deregister_service") == 0) {
353        if(strcmp(buffer, "policy_geo") == 0) {
354        }
355        else if(strcmp(buffer, "policy_time") == 0) {
356        }
357        else if(strcmp(buffer, "policy_spectrum") == 0) {
358        }
359        else if(strcmp(buffer, "policy_spacial") == 0) {
360        }
361    }*/
362
363    //Go down the list to call the appropriate function
364    if(strcmp(buffer, "query_component_type") == 0) {
365        SendComponentType();
366    }
367    else if(strcmp(buffer, "reset_sml") == 0) {
368        Reset();
369    }
370    else if(strcmp(buffer, "shutdown_sml") == 0) {
371        Shutdown();
372    }
373    else if(strcmp(buffer, "register_engine_cognitive") == 0) {
374        RegisterCognitiveEngine(ID);
375    }
376    else if(strcmp(buffer, "register_service") == 0) {
377        ReceiveServices(ID);
378    }
379    else if(strcmp(buffer, "send_component_type") == 0) {
380        SendComponentType();
381    }
382    else if(strcmp(buffer, "list_services") == 0) {
383        ListServices();
384    }
385    else if(strcmp(buffer, "set_active_mission") == 0) {
386        SetActiveMission();
387    }
388    else if(strcmp(buffer, "request_optimization") == 0) {
389        PerformActiveMission();
390    }
391    else if(strcmp(buffer, "deregister_engine_cognitive") == 0) {
392        DeregisterCognitiveEngine(ID);
393    }
394    else if(strcmp(buffer, "deregister_service") == 0) {
395        DeregisterServices(ID);
396    }
397}
398
399//TODO Finish
400/* CALLED BY: MessageHandler
401 * INPUTS: <none>
402 * OUTPUTS: <none>
403 *
404 * DESCRIPTION: Deregisters the component from the Shell.
405 */
406void
407ServiceManagementLayer::Shutdown()
408{
409    DeregisterComponent();
410}
411
412//TODO Finish
413/* CALLED BY: MessageHandler
414 * INPUTS: <none>
415 * OUTPUTS: <none>
416 *
417 * DESCRIPTION: Deregisters the component from the Shell
418 */
419void
420ServiceManagementLayer::Reset()
421{
422    DeregisterComponent();
423    ReloadConfiguration();
424}
425
426/* CALLED BY: ConnectToShell
427 * INPUTS: <none>
428 * OUTPUTS: <none>
429 *
430 * DESCRIPTION: Sends the registration message to the Shell
431 */
432void
433ServiceManagementLayer::RegisterComponent()
434{
435    SendMessage(shellSocketFD, "register_sml");
436    LOG("ServiceManagementLayer:: Registration message sent.\n");
437    //printf("SSFD = %d\n", shellSocketFD);
438}
439
440/* CALLED BY: Shutdown
441 * INPUTS: <none>
442 * OUTPUTS: <none>
443 *
444 * DESCRIPTION: Closes the client socket with the shell, sends a deregstration message
445 */
446void
447ServiceManagementLayer::DeregisterComponent()
448{
449    SendMessage(shellSocketFD, "deregister_sml");
450    LOG("ServiceManagementLayer:: Deregistration message sent.\n");
451
452    shutdown(shellSocketFD, 2);
453    close(shellSocketFD);
454    shellSocketFD = -1;
455    LOG("ServiceManagementLayer:: Shell socket closed.\n");
456}
457
458
459/* CALLED BY: RegisterCognitiveEngine
460 * INPUTS: |ID| The ID number of the component where the data is to be transfered to
461 * OUTPUTS: <none>
462 *
463 * DESCRIPTION: Streams config data directly from the shell to the CE, and checks
464 * for an "ack" message from the CE after every sent message
465 * to know when to stop communication.
466 */
467
468//Modified to check the incoming message buffer rather than the outgoing message buffer to avoid a portion of the delay
469void
470ServiceManagementLayer::TransferRadioConfiguration(int32_t ID)
471{
472    //printf("transRadConfig\n");
473    struct timeval selTimeout;
474    fd_set sockSet;
475    int32_t rc = 1;
476    char buffer[256];
477    //Send data until the CE sends an ACK message back
478    while(rc!=0){
479        memset(buffer, 0, 256);
480        //Receive data from Shell
481        ReadMessage(shellSocketFD, buffer);
482        //printf("buffer = %s\n", buffer);
483        //Send data to CE
484        SendMessage(CE_List[ID].FD, buffer);
485        FD_ZERO(&sockSet);
486        FD_SET(shellSocketFD, &sockSet);
487        selTimeout.tv_sec = 0;
488        selTimeout.tv_usec = 50000;
489        //Check if there is a message on the shell ready to be processed
490        rc=select(shellSocketFD + 1, &sockSet, NULL, NULL, &selTimeout);
491    }
492    memset(buffer, 0, 256);
493    ReadMessage(CE_List[ID].FD, buffer);
494    SendMessage(shellSocketFD, buffer);
495    //printf("transfer done!\n");
496}
497
498
499/* CALLED BY: RegisterCognitiveEngine
500 * INPUTS: |ID| The ID number of the component where the data is to be transfered to
501 * OUTPUTS: <none>
502 *
503 * DESCRIPTION: Simmilar to TransferRadioConfig, just with Experience data
504 */
505
506//Modified to check the incoming message buffer rather than the outgoing message buffer to avoid a portion of the delay
507void
508ServiceManagementLayer::TransferExperience(int32_t ID)
509{
510    struct timeval selTimeout;
511    fd_set sockSet;
512    int32_t rc = 1;
513    char buffer[256];
514    //Send data until the CE sends an ACK message back
515    while(rc!=0){
516        //printf("transfering...\n");
517        memset(buffer, 0, 256);
518        //Receive data from Shell
519        ReadMessage(shellSocketFD, buffer);
520        //printf("buffer = %s\n", buffer);
521        //Send data to CE
522        SendMessage(CE_List[ID].FD, buffer);
523        FD_ZERO(&sockSet);
524        FD_SET(shellSocketFD, &sockSet);
525        selTimeout.tv_sec = 0;
526        selTimeout.tv_usec = 50000;
527        //Check if there is a message on the shell ready to be processed
528        rc=select(shellSocketFD + 1, &sockSet, NULL, NULL, &selTimeout);
529    }
530    memset(buffer, 0, 256);
531    //printf("done trans exp!\n");
532    ReadMessage(CE_List[ID].FD, buffer);
533    SendMessage(shellSocketFD, buffer);
534}
535
536/* CALLED BY: MessageHandler
537 * INPUTS: |ID| The ID number of the component where service is located
538 * OUTPUTS: <none>
539 *
540 * DESCRIPTION: Inserts a service into the DB with the ID of the component where it exists
541 */
542void
543ServiceManagementLayer::ReceiveServices(int32_t ID)
544{
545    char buffer[256];
546    memset(buffer, 0, 256);
547    ReadMessage(CE_List[ID].FD, buffer);
548    char* cols[] = {(char *)"ID_Num", (char *)"Service_Name"};
549    //printf("RS_buffer = %s\n", buffer);
550    // generate command
551    strcpy(_services_DB->command, "insert into ");
552    strcat(_services_DB->command, _services_DB->tablename);
553    strcat(_services_DB->command, " (");
554    strcat(_services_DB->command, cols[0]);
555    strcat(_services_DB->command, ", ");
556    strcat(_services_DB->command, cols[1]);
557    strcat(_services_DB->command, ") ");
558    strcat(_services_DB->command, " values(");
559    sprintf(_services_DB->command, "%s%d", _services_DB->command, ID);
560    strcat(_services_DB->command, ", '");
561    strcat(_services_DB->command, buffer);
562    strcat(_services_DB->command, "');");
563   
564    //printf("search command: %s\n", _services_DB->command);
565    // execute add command
566    char *errorMsg;
567    int rc = sqlite3_exec(_services_DB->db, _services_DB->command, callback, 0, &errorMsg);
568    if( rc!=SQLITE_OK && rc!=101 )
569        fprintf(stderr, "ServiceManagementLayer::RecieveServices DB Error %s\n", errorMsg);
570    /*sprintf(outBuffer, "SML: Registering service '%s' from component number '%d'", buffer, ID);
571    LOG(outBuffer);*/
572}
573
574/* CALLED BY: MessageHandler
575 * INPUTS: <none>
576 * OUTPUTS: <none>
577 *
578 * DESCRIPTION: This method associates the services that components provide with the services that are requested in the mission
579 * Each service in the mission is given the ID and FD of a component that has registered to provide that service
580 * Deregistration is okay until this method is called without a reload, but if deregistration occurs after this
581 * method is called it needs to be called again even if other engines also provide the services
582 */
583void
584ServiceManagementLayer::SetActiveMission()
585{
586    char buffer[256];
587    memset(buffer, 0, 256);
588    ReadMessage(shellSocketFD, buffer);
589    uint32_t missID = atoi(buffer);
590    for(activeMission = 0; activeMission < 10; activeMission++)
591    {
592        //Find the active mission by comparing mission ID's
593        if(miss[activeMission].missionID == missID)
594            break;
595    }
596
597    LOG("ServiceManagementLayer:: Received Set Active Mission command: %i.\n",missID);
598    //For each service in the mission
599    for(uint16_t i = 0; i < miss[activeMission].numServices; i++)
600    {   
601        //Check whether the current service is an actual service or a conditional
602        if(miss[activeMission].services[i].name.compare("if") && miss[activeMission].services[i].name.compare("dowhile") && \
603           miss[activeMission].services[i].name.compare("shell")){
604            //If it is a service, search the database of registered services to find the ID of the component that registered it
605            strcpy(_services_DB->command, "select ");
606            strcat(_services_DB->command, _services_DB->tablename);
607            strcat(_services_DB->command, ".* from ");
608            strcat(_services_DB->command, _services_DB->tablename);
609            strcat(_services_DB->command, " where Service_Name==");
610            sprintf(_services_DB->command, "%s'%s';", _services_DB->command, miss[activeMission].services[i].name.c_str());
611       
612            sqlite3_stmt * pStatement;
613            int rc = sqlite3_prepare_v2(_services_DB->db, _services_DB->command, -1, &pStatement, NULL);
614            if (rc == SQLITE_OK){
615                if (sqlite3_step(pStatement) == SQLITE_ROW)
616                     miss[activeMission].services[i].componentID =  sqlite3_column_int(pStatement, 0);
617                else {
618                    printf("services_DB:: Mission requires service %s not provided by any connected component.\n",miss[activeMission].services[i].name.c_str());
619                    rc=31337;
620                }
621             } else {
622                printf("services_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_services_DB->command);
623            }
624                //printf("s_name=%s\n",miss[activeMission].services[i].name.c_str());
625            sqlite3_finalize(pStatement);
626            miss[activeMission].services[i].socketFD = CE_List[miss[activeMission].services[i].componentID].FD;
627            //Set the FD and ID of the service to refer to the component where the service exists
628        }
629        //Nothing to be done for conditionals at this stage
630    }
631 
632    SendMessage(shellSocketFD, "ack");
633    LOG("ServiceManagementLayer:: Done setting active mission.\n");
634    //printf("\nhere ---%d, %d---\n", miss[activeMission].services[0].componentID, miss[activeMission].services[1].componentID);
635}
636
637/* CALLED BY: PerformActiveMission
638 * INPUTS: |sourceID| ID of the service that is being processed
639 * OUTPUTS: <none>
640 *
641 * DESCRIPTION: This is a helper method for the "PerformActiveMission" function
642 * NOTE: This function has changed durrastically from the previous implementation
643 * Takes an ID of a service
644 * For that service, finds inputs in DB and forwords those on to the engine after sending comm-starting messages
645 * Afterwords, listenes for the outputs so that it can store those in the database for future services or the overall output
646 */
647void
648ServiceManagementLayer::TransactData(int32_t sourceID)
649{
650   // LOG("ServiceManagementLayer:: Data transaction occuring.\n");
651    char buffer[256];
652    std::string data;
653    char* cols[] = {(char *)"Tag", (char *)"Data"};
654    int i = 0;
655    fd_set sockSet;
656    char *token;
657    struct timeval selTimeout;
658
659   //Send a message directly to the shell
660   //printf("name = %s\n", miss[activeMission].services[sourceID].name.c_str());
661   if(miss[activeMission].services[sourceID].name.find("shell")!=string::npos)
662   {
663        //printf("caught shell\n");
664        //If the name on the output doesn't start with "~", search the DB to find the output that should be returned
665        if(miss[activeMission].services[sourceID].output[0].find("~") == string::npos){
666           // printf("taken1\n");
667            memset(buffer, 0 , 256);
668            strcpy(_data_DB->command, "select ");
669            strcat(_data_DB->command, _data_DB->tablename);
670            strcat(_data_DB->command, ".* from ");
671            strcat(_data_DB->command, _data_DB->tablename);
672            strcat(_data_DB->command, " where Tag==");
673            sprintf(_data_DB->command, "%s'%s';", _data_DB->command, miss[activeMission].services[sourceID].output[0].c_str());
674            sqlite3_stmt * pStatement;
675            int rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, -1, &pStatement, NULL);
676            if (rc == SQLITE_OK){
677                if (sqlite3_step(pStatement) == SQLITE_ROW)
678                    data.append((const char*) sqlite3_column_text(pStatement, 1));
679                else {
680                    //TODO could do shell output here if not in DB
681                data.append("1@");
682                data.append(miss[activeMission].services[sourceID].output[0]);
683                data.append("@");
684                data.append(miss[activeMission].services[sourceID].output[0]);
685                data.append("@");
686                //printf("data = %s\n", data.c_str());
687               
688                    printf("data_DB:: Data not yet in DB.\n");
689                    rc=31337;
690                }
691            }
692            else {
693                printf("data_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_data_DB->command);
694            }
695            sqlite3_finalize(pStatement);
696            token = strtok((char *)data.c_str(), "@");
697            SendMessage(shellSocketFD, token);
698            token = strtok(NULL, "@");
699            while(token){
700                SendMessage(shellSocketFD, token);
701                token = strtok(NULL, "@");
702            }
703        }
704        //printf("done shell\n");
705       // LOG("ServiceManagementLayer:: Finished with data transaction.\n");
706        return;
707   }
708
709
710    //If this is a service command and not a shell command...
711    //Transmission starting messages
712    SendMessage(miss[activeMission].services[sourceID].socketFD, "request_optimization_service");
713    SendMessage(miss[activeMission].services[sourceID].socketFD, miss[activeMission].services[sourceID].name.c_str());
714    //Find and load the input data
715    while(i < 5 && !miss[activeMission].services[sourceID].input[i].empty()){
716        //printf("pulling input data out of DB for ID#=%d\n", sourceID);
717        strcpy(_data_DB->command, "select ");
718        strcat(_data_DB->command, _data_DB->tablename);
719        strcat(_data_DB->command, ".* from ");
720        strcat(_data_DB->command, _data_DB->tablename);
721        strcat(_data_DB->command, " where Tag==");
722        char temp[100];
723        strcpy(temp, miss[activeMission].services[sourceID].input[i].c_str());
724        char *temp2 = strtok(temp, "+");
725        sprintf(_data_DB->command, "%s'%s';", _data_DB->command, temp2);
726        sqlite3_stmt * pStatement;
727        int rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, -1, &pStatement, NULL);
728        if (rc == SQLITE_OK){
729            if (sqlite3_step(pStatement) == SQLITE_ROW)
730                 data.append((const char*) sqlite3_column_text(pStatement, 1));
731            else {
732                    printf("data_DB:: Data not yet in DB.\n");
733                    rc=31337;
734            }
735        }
736        else {
737            printf("data_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_data_DB->command);
738        }
739        sqlite3_finalize(pStatement);
740        char *data_ch = (char *) data.c_str();
741        int32_t numStatements = 0;
742        temp2 = strtok(NULL, "+");
743        while(temp2){
744            numStatements++;
745            temp2 = strtok(NULL, "+");
746        }
747        //printf("here1%d\n", numStatements);
748        char temp4[10];
749        memset(temp4, 0, 10);
750        sprintf(temp4, "%d", numStatements);
751        //Tokenize the data and pass it along
752        //printf("here2 %s\n", temp4);
753        if(strstr(miss[activeMission].services[sourceID].input[i].c_str(), "+")){
754            SendMessage(miss[activeMission].services[sourceID].socketFD, temp4);
755            token = strtok(data_ch, "@");
756        }
757        else{
758            token = strtok(data_ch, "@");
759            SendMessage(miss[activeMission].services[sourceID].socketFD, token);
760        }
761        token = strtok(NULL, "@");
762
763
764        //Either have to send whole block of memory or just one piece
765        while(token){
766            if(strstr(miss[activeMission].services[sourceID].input[i].c_str(), token))
767            {
768                //printf("1tokenizing %s %s!\n", miss[activeMission].services[sourceID].input[i].c_str(), token);
769                SendMessage(miss[activeMission].services[sourceID].socketFD, token);
770                token = strtok(NULL, "@");
771                SendMessage(miss[activeMission].services[sourceID].socketFD, token);
772            }
773            else if(!strstr(miss[activeMission].services[sourceID].input[i].c_str(), "+"))
774            {
775                //printf("t not detected tokenizing %s %s!\n", miss[activeMission].services[sourceID].input[i].c_str(), token);
776                SendMessage(miss[activeMission].services[sourceID].socketFD, token);
777                token = strtok(NULL, "@");
778                SendMessage(miss[activeMission].services[sourceID].socketFD, token);
779            }
780            else{
781                //printf("3tokenizing %s %s!\n", miss[activeMission].services[sourceID].input[i].c_str(), token);
782                token = strtok(NULL, "@");}
783            token = strtok(NULL, "@");
784        }
785        //printf("done\n");
786        //printf("done pulling input data out of DB for ID#=%d\n", sourceID);
787        i++;
788        data.clear();
789    }
790    int32_t j = 0;
791    FD_ZERO(&sockSet);
792    FD_SET(miss[activeMission].services[sourceID].socketFD, &sockSet);
793    //TODO neccessary?
794    selTimeout.tv_sec = 5;
795    selTimeout.tv_usec = 0;
796    //Use select command to force wait for processing to finish
797    select(miss[activeMission].services[sourceID].socketFD + 1, &sockSet, NULL, NULL, &selTimeout);
798        //printf("done\n");
799   //TODO rewrite part of data on output?
800   //TODO true false format?
801    while(j < 5 && !miss[activeMission].services[sourceID].output[j].empty()){
802        int rc;
803        memset(buffer, 0, 256);
804        ReadMessage(miss[activeMission].services[sourceID].socketFD, buffer);
805       // printf("waiting\n");     
806        data.append(buffer);
807        data.append("@");
808        int t = atoi(buffer);
809        //printf("%d\n", t);
810        for(int k = 0; k < t; k++){
811            //Read the data incrementally and deliminate it with the "@" symbol
812            memset(buffer, 0, 256);
813            ReadMessage(miss[activeMission].services[sourceID].socketFD, buffer);
814            if(!strcmp(buffer, "TF")){
815                ReadMessage(miss[activeMission].services[sourceID].socketFD, buffer);
816                data.append(buffer);
817                data.append("@");
818            }
819            else{
820                data.append(buffer);
821                data.append("@");
822                memset(buffer, 0, 256);
823                ReadMessage(miss[activeMission].services[sourceID].socketFD, buffer);
824                data.append(buffer);
825                data.append("@");
826            }
827        }
828        //printf("SML: putting output data into DB for ID#=%d\n", sourceID);
829
830        strcpy(_data_DB->command, "insert or replace into ");
831        strcat(_data_DB->command, _data_DB->tablename);
832        strcat(_data_DB->command, " (");
833        strcat(_data_DB->command, cols[0]);
834        strcat(_data_DB->command, ", ");
835        strcat(_data_DB->command, cols[1]);
836        strcat(_data_DB->command, ") ");
837        strcat(_data_DB->command, " values('");
838        strcat(_data_DB->command, miss[activeMission].services[sourceID].output[j].c_str());
839        strcat(_data_DB->command, "', '");
840        strcat(_data_DB->command, data.c_str());
841        strcat(_data_DB->command, "');");
842        char *errorMsg;
843        rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
844        if( rc!=SQLITE_OK && rc!=101 )
845            fprintf(stderr, "SQL error: %s\n", errorMsg);
846        //printf("S: done putting ouptut data into DB for ID#='%d', data=%s\n", sourceID, data.c_str());
847        j++;
848        data.clear();
849    }
850    //printf("done transact data!\n");
851   // LOG("ServiceManagementLayer:: Finished with data transaction.\n");
852
853
854    /*printf("\n\n\n");
855    // generate commandi
856    strcpy(_data_DB->command, "select ");
857    strcat(_data_DB->command, _data_DB->tablename);
858    strcat(_data_DB->command, ".* from ");
859    strcat(_data_DB->command, _data_DB->tablename);
860    strcat(_data_DB->command, ";");
861
862    // execute print (select all)  command   
863    char *errorMsg;
864    int rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
865    if( rc!=SQLITE_OK && rc!=101 )
866        fprintf(stderr, "SQL error: %s\n", errorMsg);
867    printf("database %s, table %s:\n", _data_DB->filename, _data_DB->tablename);
868    printf("\n\n\n");*/
869}
870
871
872
873/* CALLED BY: MessageHandler
874 * INPUTS: <none>
875 * OUTPUTS: <none>
876 *
877 * DESCRIPTION: This function works by first sending the inputs from the shell to the appropriate components
878 * The first service should begin immeadiately, as should any others who have all of their input paramaters
879 * When they complete, the output path is found and the data is transfered as it becomes available
880 * Presumably at this point the second function has all of it's paramaters, so it begins to compute, and the cycle repeats
881 * 
882 *
883 * Rules for active missions (currently)
884 * -Five inputs/outputs per service and per mission
885 * -All ordering constraints have been relaxed in this version; all data is stored locally and only sent when requested
886 * -If support fully implemented - up to three levels
887 * -While support still a work in progress
888 * -IMPORTANT: DB uses '@' to seperate individual statements; using '@' in the data stream will result in incorrect behavior
889 */
890
891//IF-IF-IF
892//WHILE
893void
894ServiceManagementLayer::PerformActiveMission()
895{
896    uint16_t i = 0;
897    std::string data_param, data_obsv, data;
898    std::string input;
899    std::string check;
900    char buffer[256];
901    char buffer1[256];
902    char *token;
903    int rc;
904    char *errorMsg;
905    char* cols[] = {(char *)"Tag", (char *)"Data"};
906    //Get the inputs
907    memset(buffer, 0, 256);
908    ReadMessage(shellSocketFD, buffer);
909    LOG("ServiceManagementLayer:: Received PerformActiveMission command.\n");
910
911    int32_t t = atoi(buffer);
912    /* Receive Set of Observables */
913    for(int32_t m = 0; m < t; m++) {
914        //printf("data=%s\n", data_obsv.c_str());
915        memset(buffer1, 0, 256);
916        ReadMessage(shellSocketFD, buffer1);
917        strcpy(_data_DB->command, "insert into ");
918        strcat(_data_DB->command, _data_DB->tablename);
919        strcat(_data_DB->command, " (");
920        strcat(_data_DB->command, cols[0]);
921        strcat(_data_DB->command, ", ");
922        strcat(_data_DB->command, cols[1]);
923        strcat(_data_DB->command, ") ");
924        memset(buffer, 0, 256);
925        ReadMessage(shellSocketFD, buffer);
926        sprintf(_data_DB->command, "%s values('%s', '1@%s@%s", _data_DB->command, buffer1, buffer1, buffer);
927        strcat(_data_DB->command, "');");
928        rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
929        if( rc!=SQLITE_OK && rc!=101 )
930            fprintf(stderr, "SQL error: %s\n", errorMsg);
931    }
932
933    /* Receive Set of Parameters */
934    memset(buffer, 0, 256);
935    ReadMessage(shellSocketFD, buffer);
936    t=atoi(buffer);
937    for(int m = 0; m < t; m++) {
938        //printf("data=%s\n", data_obsv.c_str());
939        memset(buffer1, 0, 256);
940        ReadMessage(shellSocketFD, buffer1);
941        strcpy(_data_DB->command, "insert into ");
942        strcat(_data_DB->command, _data_DB->tablename);
943        strcat(_data_DB->command, " (");
944        strcat(_data_DB->command, cols[0]);
945        strcat(_data_DB->command, ", ");
946        strcat(_data_DB->command, cols[1]);
947        strcat(_data_DB->command, ") ");
948        memset(buffer, 0, 256);
949        ReadMessage(shellSocketFD, buffer);
950        sprintf(_data_DB->command, "%s values('%s', '1@%s@%s');", _data_DB->command, buffer1, buffer1, buffer);
951        rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
952        if( rc!=SQLITE_OK && rc!=101 )
953            fprintf(stderr, "SQL error: %s\n", errorMsg);
954    }
955
956
957
958
959
960    while(i < 5 && !miss[activeMission].input[i].empty()){
961            //New data being added to DB
962        //printf("inserting data from shell\n");
963        memset(buffer1, 0, 256);
964        ReadMessage(shellSocketFD, buffer1);
965        t=atoi(buffer1);
966        //printf("t=%d\n", t);
967        for(int m = 0; m < t; m++) {
968            data.append("@");
969            memset(buffer, 0, 256);
970            ReadMessage(shellSocketFD, buffer);
971            data.append(buffer);
972            data.append("@");
973            memset(buffer, 0, 256);
974            ReadMessage(shellSocketFD, buffer);
975            data.append(buffer);
976        }
977        //printf("here %s\n", data.c_str());
978        strcpy(_data_DB->command, "insert into ");
979        strcat(_data_DB->command, _data_DB->tablename);
980        strcat(_data_DB->command, " (");
981        strcat(_data_DB->command, cols[0]);
982        strcat(_data_DB->command, ", ");
983        strcat(_data_DB->command, cols[1]);
984        strcat(_data_DB->command, ") ");
985        strcat(_data_DB->command, " values('");
986        strcat(_data_DB->command, miss[activeMission].input[i].c_str());
987        sprintf(_data_DB->command, "%s', '%s%s');", _data_DB->command, buffer1, data.c_str());
988        char *errorMsg;
989        rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
990        if( rc!=SQLITE_OK && rc!=101 )
991            fprintf(stderr, "SQL error: %s\n", errorMsg);
992        //printf("SML: finished adding data from shell on input %d\n", i);
993        i++;
994        data.clear();
995    }
996
997
998    //Useful for spotchecking what's in the database
999    /*printf("\n\n\n");
1000    // generate commandi
1001    strcpy(_data_DB->command, "select ");
1002    strcat(_data_DB->command, _data_DB->tablename);
1003    strcat(_data_DB->command, ".* from ");
1004    strcat(_data_DB->command, _data_DB->tablename);
1005    strcat(_data_DB->command, ";");
1006
1007    // execute print (select all)  command 
1008    rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
1009    if( rc!=SQLITE_OK && rc!=101 )
1010        fprintf(stderr, "SQL error: %s\n", errorMsg);
1011    printf("database %s, table %s:\n", _data_DB->filename, _data_DB->tablename);
1012    printf("\n\n\n");*/
1013
1014
1015
1016
1017   // printf("done\n");
1018    i=0;
1019    int32_t numstatements[3] = {0,0,0};
1020    while(i < miss[activeMission].numServices)
1021    {
1022        if(miss[activeMission].services[i].name.compare("if")==0)
1023        {
1024           //printf("L0:if detected\n");
1025            input.clear();
1026            check.clear();
1027            int t;
1028            for(t = 0; t < 5; t++){
1029                if(!miss[activeMission].services[i].output[t].empty()){
1030                    //printf("i-numstmts-1 = %d\n", i-numstatements[0]-1);
1031                    input=miss[activeMission].services[i-numstatements[0]-1].output[t];
1032                    strcpy(_data_DB->command, "SELECT ");
1033                    strcat(_data_DB->command, _data_DB->tablename);
1034                    strcat(_data_DB->command, ".* from ");
1035                    strcat(_data_DB->command, _data_DB->tablename);
1036                    strcat(_data_DB->command, " where Tag==");
1037                    sprintf(_data_DB->command, "%s'%s';", _data_DB->command, input.c_str());
1038                    sqlite3_stmt * pStatement;
1039                    rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, -1, &pStatement, NULL);
1040                    if (rc == SQLITE_OK){
1041                        if (sqlite3_step(pStatement) == SQLITE_ROW)
1042                             data = (const char *) sqlite3_column_text(pStatement, 1);
1043                        else {
1044                                printf("1 data_DB:: Data not yet in DB.\n");
1045                                rc=31337;
1046                        }
1047                    } else {
1048                        printf("data_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_data_DB->command);
1049                    }
1050                    sqlite3_finalize(pStatement);
1051                    //printf("data=%s\n", data.c_str());
1052                    token = strtok((char *)data.c_str(), "@");
1053                    token = strtok(NULL, "@");
1054                    token = strtok(NULL, "@");
1055                    //printf("data=%s\n", token);
1056                    break;
1057                }
1058            }
1059            //printf("L0:--- %s  %s---\n", miss[activeMission].services[i].output[t].c_str(), token);
1060            //TODO change to strstr
1061            if(strstr(miss[activeMission].services[i].output[t].c_str(), token)){
1062                //printf("L0:if taken\n");
1063                for(uint16_t k = i+1; k <= i+miss[activeMission].services[i].num_conds; k++){
1064                        //printf("transacting data for k=%d\n", k);
1065                    //printf("%s---%d\n", miss[activeMission].services[k].name.c_str(), k);
1066                    if(miss[activeMission].services[k].name.compare("if")==0){
1067                        //printf("L1:if detected\n");
1068                            input.clear();
1069                            check.clear();
1070                            for(t = 0; t < 5; t++){
1071                                if(!miss[activeMission].services[k].output[t].empty()){
1072                                    //printf("i-numstmts = %d\n", i-numstatements-1);
1073                                    input=miss[activeMission].services[k-numstatements[1]-1].output[t];
1074                                    strcpy(_data_DB->command, "SELECT ");
1075                                    strcat(_data_DB->command, _data_DB->tablename);
1076                                    strcat(_data_DB->command, ".* from ");
1077                                    strcat(_data_DB->command, _data_DB->tablename);
1078                                    strcat(_data_DB->command, " where Tag==");
1079                                    sprintf(_data_DB->command, "%s'%s';", _data_DB->command, input.c_str());
1080                                    sqlite3_stmt * pStatement;
1081                                    rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, -1, &pStatement, NULL);
1082                                    if (rc == SQLITE_OK){
1083                                        if (sqlite3_step(pStatement) == SQLITE_ROW)
1084                                             data = (const char *) sqlite3_column_text(pStatement, 1);
1085                                        else {
1086                                                printf("1 data_DB:: Data not yet in DB.\n");
1087                                                rc=31337;
1088                                        }
1089                                    } else {
1090                                        printf("data_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_data_DB->command);
1091                                    }
1092                                    sqlite3_finalize(pStatement);
1093                                    //printf("data=%s\n", data.c_str());
1094                                    token = strtok((char *)data.c_str(), "@");
1095                                    token = strtok(NULL, "@");
1096                                    token = strtok(NULL, "@");
1097                                    //printf("data=%s\n", token);
1098                                    break;
1099                                }
1100                            }
1101                            //printf("L1:--- %s  %s---\n", miss[activeMission].services[k].output[t].c_str(), token);
1102                            //TODO change to strstr
1103                            if(strstr(miss[activeMission].services[k].output[t].c_str(), token)){
1104                                //printf("L1:if taken\n");
1105                                for(uint16_t j = k+1; j <= k+miss[activeMission].services[k].num_conds; j++){
1106                                    //printf("transacting data for k=%d\n", k);
1107                                    //printf("%s---%d\n", miss[activeMission].services[j].name.c_str(), j);
1108                                    if(miss[activeMission].services[j].name.compare("if")==0){
1109                                        //printf("L2:if detected\n");
1110                                            input.clear();
1111                                            check.clear();
1112                                            for(t = 0; t < 5; t++){
1113                                                if(!miss[activeMission].services[j].output[t].empty()){
1114                                                    //printf("i-numstmts = %d\n", i-numstatements-1);
1115                                                    input=miss[activeMission].services[j-numstatements[2]-1].output[t];
1116                                                    strcpy(_data_DB->command, "SELECT ");
1117                                                    strcat(_data_DB->command, _data_DB->tablename);
1118                                                    strcat(_data_DB->command, ".* from ");
1119                                                    strcat(_data_DB->command, _data_DB->tablename);
1120                                                    strcat(_data_DB->command, " where Tag==");
1121                                                    sprintf(_data_DB->command, "%s'%s';", _data_DB->command, input.c_str());
1122                                                    sqlite3_stmt * pStatement;
1123                                                    rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, -1, &pStatement, NULL);
1124                                                    if (rc == SQLITE_OK){
1125                                                        if (sqlite3_step(pStatement) == SQLITE_ROW)
1126                                                             data = (const char *) sqlite3_column_text(pStatement, 1);
1127                                                        else {
1128                                                                printf("1 data_DB:: Data not yet in DB.\n");
1129                                                                rc=31337;
1130                                                        }
1131                                                    } else {
1132                                                        printf("data_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_data_DB->command);
1133                                                    }
1134                                                    sqlite3_finalize(pStatement);
1135                                                    //printf("data=%s\n", data.c_str());
1136                                                    token = strtok((char *)data.c_str(), "@");
1137                                                    token = strtok(NULL, "@");
1138                                                    token = strtok(NULL, "@");
1139                                                    //printf("data=%s\n", token);
1140                                                    break;
1141                                                }
1142                                            }
1143                                            //printf("L2:--- %s  %s---\n", miss[activeMission].services[j].output[t].c_str(), token);
1144                                            //TODO change to strstr
1145                                            if(strstr(miss[activeMission].services[j].output[t].c_str(), token)){
1146                                                //printf("L1:if taken\n");
1147                                                for(uint16_t l = j+1; l <= j+miss[activeMission].services[j].num_conds; l++){
1148                                                    //printf("transacting data for k=%d\n", k);
1149                                                    TransactData(l);
1150                                                }
1151                                            }
1152                                            else
1153                                                //printf("L2: if not taken\n");
1154                                                numstatements[2] +=miss[activeMission].services[j].num_conds+1;
1155                                                j+=miss[activeMission].services[j].num_conds;
1156                                            //printf("doneif %d, %d, %d\n", numstatements, miss[activeMission].services[i].num_conds, i);
1157                                        }
1158                                        else{
1159                                            //printf("NO L2 COND!\n");
1160                                            numstatements[2]=0;
1161                                            TransactData(j);
1162                                        }
1163                                }
1164                            }
1165                            else
1166                                //printf("L1: if not taken\n");
1167                                numstatements[1] +=miss[activeMission].services[k].num_conds+1;
1168                                k+=miss[activeMission].services[k].num_conds;
1169                            //printf("doneif %d, %d, %d\n", numstatements, miss[activeMission].services[i].num_conds, i);
1170                        } else if(miss[activeMission].services[k].name.compare("dowhile")==0){
1171                            //printf("while detected\n");
1172                            while(true){
1173                                uint16_t m;
1174                                for(uint16_t m = k+1; m <= k+miss[activeMission].services[k].num_conds; m++){
1175                                    TransactData(m);
1176                                    printf("transact! %d\n", m);
1177                                }
1178                                    data.clear();
1179                                    printf("L1:while detected %d, %d\n", miss[activeMission].services[k].num_conds, k);
1180                                    input.clear();
1181                                    check.clear();
1182                                    int t;
1183                                    for(t = 0; t < 5; t++){
1184                                        if(!miss[activeMission].services[k-1].output[t].empty()){
1185                                            input=miss[activeMission].services[m].output[t];
1186                                            strcpy(_data_DB->command, "SELECT ");
1187                                            strcat(_data_DB->command, _data_DB->tablename);
1188                                            strcat(_data_DB->command, ".* from ");
1189                                            strcat(_data_DB->command, _data_DB->tablename);
1190                                            strcat(_data_DB->command, " where Tag==");
1191                                            sprintf(_data_DB->command, "%s'%s';", _data_DB->command, input.c_str());
1192                                            sqlite3_stmt * pStatement;
1193                                            rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, -1, &pStatement, NULL);
1194                                            if (rc == SQLITE_OK){
1195                                                if (sqlite3_step(pStatement) == SQLITE_ROW)
1196                                                     data = (const char *) sqlite3_column_text(pStatement, 1);
1197                                                else {
1198                                                        printf("1 data_DB:: Data not yet in DB.\n");
1199                                                        rc=31337;
1200                                                }
1201                                            } else {
1202                                                printf("data_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_data_DB->command);
1203                                            }
1204                                            sqlite3_finalize(pStatement);
1205                                            //printf("data=%s\n", data.c_str());
1206                                            token = strtok((char *)data.c_str(), "@");
1207                                            token = strtok(NULL, "@");
1208                                            token = strtok(NULL, "@");
1209                                            //printf("data=%s\n", token);
1210                                            break;
1211                                        }
1212                                    }
1213                                    printf("L1:--- %s  %s---\n", miss[activeMission].services[k].output[t].c_str(), token);
1214                                    if(strstr(miss[activeMission].services[k].output[t].c_str(), token)){
1215                                        printf("L1:do it again!\n");
1216                                    }
1217                                    else
1218                                        break;
1219                            }
1220                            k+=miss[activeMission].services[k].num_conds;
1221                            //printf("donewhile\n");
1222                        }
1223                        else{
1224                            //printf("NO L1 COND!\n");
1225                            numstatements[1]=0;
1226                            TransactData(k);
1227                        }
1228               
1229                        //numstatements[0] +=miss[activeMission].services[i].num_conds+1;
1230                        //i+=miss[activeMission].services[i].num_conds;
1231            //printf("doneif %d, %d, %d\n", numstatements, miss[activeMission].services[i].num_conds, i);
1232                }
1233            }
1234           // else
1235                //printf("LO if not taken\n");
1236            numstatements[0] +=miss[activeMission].services[i].num_conds+1;
1237            i+=miss[activeMission].services[i].num_conds;
1238            //printf("doneif %d, %d, %d\n", numstatements, miss[activeMission].services[i].num_conds, i);
1239        }
1240        else if(miss[activeMission].services[i].name.compare("dowhile")==0)
1241        {
1242            numstatements[0]=0;
1243            //printf("while detected\n");
1244            while(true){
1245                uint16_t k;
1246                    for(k = i+1; k <= i+miss[activeMission].services[i].num_conds; k++){
1247                        TransactData(k);
1248                    }
1249                    data.clear();
1250                    //printf("L0:while detected %d, %d\n", k, miss[activeMission].services[i].num_conds);
1251                    input.clear();
1252                    check.clear();
1253                    int t;
1254                    for(t = 0; t < 5; t++){
1255                        if(!miss[activeMission].services[i].output[t].empty()){
1256                            input=miss[activeMission].services[k-1].output[t];
1257                            //printf("input=%s\n", input.c_str());
1258                            strcpy(_data_DB->command, "SELECT ");
1259                            strcat(_data_DB->command, _data_DB->tablename);
1260                            strcat(_data_DB->command, ".* from ");
1261                            strcat(_data_DB->command, _data_DB->tablename);
1262                            strcat(_data_DB->command, " where Tag==");
1263                            sprintf(_data_DB->command, "%s'%s';", _data_DB->command, input.c_str());
1264                            sqlite3_stmt * pStatement;
1265                            rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, -1, &pStatement, NULL);
1266                            if (rc == SQLITE_OK){
1267                                if (sqlite3_step(pStatement) == SQLITE_ROW)
1268                                     data = (const char *) sqlite3_column_text(pStatement, 1);
1269                                else {
1270                                        printf("1 data_DB:: Data not yet in DB.\n");
1271                                        rc=31337;
1272                                }
1273                            } else {
1274                                printf("data_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_data_DB->command);
1275                            }
1276                            sqlite3_finalize(pStatement);
1277                            //printf("data=%s\n", data.c_str());
1278                            token = strtok((char *)data.c_str(), "@");
1279                            token = strtok(NULL, "@");
1280                            token = strtok(NULL, "@");
1281                            //printf("data=%s\n", token);
1282                            break;
1283                        }
1284                    }
1285                    //printf("L0:--- %s  %s---\n", miss[activeMission].services[i].output[t].c_str(), token);
1286                    if(strstr(miss[activeMission].services[i].output[t].c_str(), token)){
1287                        //printf("L0:while taken again!\n");
1288                    }
1289                    else
1290                        break;
1291            }
1292            i+=miss[activeMission].services[i].num_conds;
1293            //printf("doneif\n");
1294        }
1295        else{
1296            numstatements[0]=0;
1297            //printf("L0 Neither if nor while\n");
1298            TransactData(i);}
1299        i++;
1300        //printf("i=%d\n", i);
1301    }
1302    i=0;
1303    data.clear();
1304    //get the ouptuts
1305    while(i < 5 && !miss[activeMission].output[i].empty()){
1306        //printf("sending output data to shell\n");
1307        strcpy(_data_DB->command, "select ");
1308        strcat(_data_DB->command, _data_DB->tablename);
1309        strcat(_data_DB->command, ".* from ");
1310        strcat(_data_DB->command, _data_DB->tablename);
1311        strcat(_data_DB->command, " where Tag==");
1312        sprintf(_data_DB->command, "%s'%s';", _data_DB->command, miss[activeMission].output[i].c_str());
1313        sqlite3_stmt * pStatement;
1314        int rc = sqlite3_prepare_v2(_data_DB->db, _data_DB->command, -1, &pStatement, NULL);
1315        if (rc == SQLITE_OK){
1316            if (sqlite3_step(pStatement) == SQLITE_ROW)
1317                 data.append((const char*) sqlite3_column_text(pStatement, 1));
1318            else {
1319                    printf("data_DB:: Data not yet in DB.\n");
1320                    rc=31337;
1321            }
1322        }
1323        else {
1324            printf("services_DB:: Error executing SQL statement. rc = %i\n%s\n",rc,_data_DB->command);
1325        }
1326        //printf("here %s\n", data.c_str());
1327        sqlite3_finalize(pStatement);
1328        char *data_ch = (char *) data.c_str();
1329        char *token = strtok(data_ch, "@");
1330        SendMessage(shellSocketFD, token);
1331        token = strtok(NULL, "@");
1332        while(token){
1333            SendMessage(shellSocketFD, token);
1334            //printf("token1 = %s\n", token);
1335            token = strtok(NULL, "@");
1336            SendMessage(shellSocketFD, token);
1337            //printf("token2 = %s\n", token);
1338            token = strtok(NULL, "@");
1339        }
1340        i++;
1341        data.clear();
1342    }
1343    LOG("ServiceManagementLayer:: Done sending output data to shell from PerformActiveMission.\n");
1344    strcpy(_data_DB->command, "select ");
1345    strcat(_data_DB->command, _data_DB->tablename);
1346    strcat(_data_DB->command, ".* from ");
1347    strcat(_data_DB->command, _data_DB->tablename);
1348    strcat(_data_DB->command, ";");
1349
1350    // execute print (select all)  command 
1351    rc = sqlite3_exec(_data_DB->db, _data_DB->command, callback, 0, &errorMsg);
1352    if( rc!=SQLITE_OK && rc!=101 )
1353        fprintf(stderr, "SQL error: %s\n", errorMsg);
1354    printf("database %s, table %s:\n", _data_DB->filename, _data_DB->tablename);
1355    printf("\n\n\n");
1356}
1357
1358
1359/* CALLED BY: MessageHandler
1360 * INPUTS: <none>
1361 * OUTPUTS: <none>
1362 *
1363 * DESCRIPTION: Print a list of the services currently registered and the ID's of the components that registered them
1364 */
1365void
1366ServiceManagementLayer::ListServices()
1367{
1368    // generate commandi
1369    strcpy(_services_DB->command, "select ");
1370    strcat(_services_DB->command, _services_DB->tablename);
1371    strcat(_services_DB->command, ".* from ");
1372    strcat(_services_DB->command, _services_DB->tablename);
1373    strcat(_services_DB->command, ";");
1374
1375    // execute print (select all)  command   
1376    char *errorMsg;
1377    int rc = sqlite3_exec(_services_DB->db, _services_DB->command, callback, 0, &errorMsg);
1378    if( rc!=SQLITE_OK && rc!=101 )
1379        fprintf(stderr, "SQL error: %s\n", errorMsg);
1380    printf("database %s, table %s:\n", _services_DB->filename, _services_DB->tablename);
1381}
1382
1383/* CALLED BY: Reset
1384 * INPUTS: <none>
1385 * OUTPUTS: <none>
1386 *
1387 * DESCRIPTION: Clear and reinitialize the mission array, then reload the configuration file
1388 */
1389void
1390ServiceManagementLayer::ReloadConfiguration()
1391{
1392    LOG("ServiceManagementLayer:: Reloading Configuration.\n");
1393    free(miss);
1394    miss = new Mission[10];
1395    for(int i = 0; i < 10; i++)
1396        miss[i].services = new Service[20];
1397    LoadConfiguration(_SML_Config, miss);
1398}
1399
1400/* CALLED BY: constructor
1401 * INPUTS: |SML_Config| Address (either relitive or full) of the XML file containing mission data
1402 *         |mList| Mission array to be modified
1403 * OUTPUTS: <none>
1404 *
1405 * DESCRIPTION: IMPORTANT - See formatting instructions for correct parsing of data
1406 * Can currently handle 5 inputs and 5 outputs per service, but easily expandable
1407 * Also, can handle two layer of nested conditional statements, but could
1408 * be expanded to meet additional needs.
1409 *
1410 * Components assigned to mission during "set active mission" stage so that
1411 * components can still continue to register after the configuration is loaded
1412 */
1413void
1414ServiceManagementLayer::LoadConfiguration(const char *SML_Config, Mission* &mList)
1415{
1416    TiXmlElement *pMission;
1417    TiXmlElement *pService;
1418    TiXmlElement *pChild0, *pChild1, *pChild2, *pChild3, *pChild4;
1419    TiXmlHandle hRoot(0);
1420    printf("ServiceManagementLayer:: Loading Configuration.\n");
1421    TiXmlDocument doc(".");
1422    doc.LoadFile(SML_Config);
1423    bool loadOkay = doc.LoadFile();
1424    if(!loadOkay)
1425        printf("Loading SML configuration failed: %s\n", SML_Config);
1426
1427    TiXmlHandle hDoc(&doc);
1428   
1429    pMission = hDoc.FirstChildElement().Element();
1430
1431    if(!pMission)
1432        printf("No valid root!");
1433
1434    hRoot = TiXmlHandle(pMission);
1435    pService = pMission->FirstChildElement();
1436    int32_t mission_num = 0;
1437    //Iterate through the missions
1438    for(pChild0 = pMission->FirstChildElement(); pChild0 ; \
1439        pChild0 = pChild0->NextSiblingElement())
1440    {
1441        int32_t service_num = 0;
1442        uint16_t cond_array[] = {0, 0, 0};
1443        //printf("mission_num = %d\n", mission_num);
1444        //memset(cond_array, 0, 2);
1445       
1446        for(pChild1  = pChild0->FirstChildElement(); pChild1; \
1447            pChild1  = pChild1->NextSiblingElement())
1448        {
1449            int32_t conditional_0 = service_num;
1450            for(pChild2 = pChild1->FirstChildElement(); \
1451                pChild2; pChild2 = pChild2->NextSiblingElement())
1452            {
1453                service_num++;
1454                int32_t conditional_1 = service_num;
1455                for(pChild3 = pChild2->FirstChildElement(); \
1456                    pChild3; pChild3 = pChild3->NextSiblingElement())
1457                {
1458                    service_num++;
1459                    int32_t conditional_2 = service_num;
1460                        for(pChild4 = pChild3->FirstChildElement(); \
1461                            pChild4; pChild4 = pChild4->NextSiblingElement())
1462                        {
1463                            service_num++;
1464                            if(pChild4->Attribute("name"))
1465                                mList[mission_num].services[service_num].name = pChild4->Attribute("name");
1466                            else
1467                                mList[mission_num].services[service_num].name = pChild4->Value();
1468                               
1469                            if(pChild4->Attribute("input1"))
1470                                mList[mission_num].services[service_num].input[0] = pChild4->Attribute("input1");
1471                            if(pChild4->Attribute("input2"))
1472                                mList[mission_num].services[service_num].input[1] = pChild4->Attribute("input2");
1473                            if(pChild4->Attribute("input3"))
1474                                mList[mission_num].services[service_num].input[2] = pChild4->Attribute("input3");
1475                            if(pChild4->Attribute("input4"))
1476                                mList[mission_num].services[service_num].input[3] = pChild4->Attribute("input4");
1477                            if(pChild4->Attribute("input5"))
1478                                mList[mission_num].services[service_num].input[4] = pChild4->Attribute("input5");
1479                            if(pChild4->Attribute("output1"))
1480                                mList[mission_num].services[service_num].output[0] = pChild4->Attribute("output1");
1481                            if(pChild4->Attribute("output2"))
1482                                mList[mission_num].services[service_num].output[1] = pChild4->Attribute("output2");
1483                            if(pChild4->Attribute("output3"))
1484                                mList[mission_num].services[service_num].output[2] = pChild4->Attribute("output3");
1485                            if(pChild4->Attribute("output4"))
1486                                mList[mission_num].services[service_num].output[3] = pChild4->Attribute("output4");
1487                            if(pChild4->Attribute("output5"))
1488                                mList[mission_num].services[service_num].output[4] = pChild4->Attribute("output5");
1489                            cond_array[2]++;
1490                        }
1491                        if(!strcmp(pChild3->Value(), "shell") || conditional_2 != service_num) {
1492                            mList[mission_num].services[conditional_2].name = pChild3->Value();
1493                        }
1494                        else{
1495                            mList[mission_num].services[service_num].name = pChild3->Attribute("name");
1496                        }
1497                            if(pChild3->Attribute("input1"))
1498                                mList[mission_num].services[conditional_2].input[0] = pChild3->Attribute("input1");
1499                            if(pChild3->Attribute("input2"))
1500                                mList[mission_num].services[conditional_2].input[1] = pChild3->Attribute("input2");
1501                            if(pChild3->Attribute("input3"))
1502                                mList[mission_num].services[conditional_2].input[2] = pChild3->Attribute("input3");
1503                            if(pChild3->Attribute("input4"))
1504                                mList[mission_num].services[conditional_2].input[3] = pChild3->Attribute("input4");
1505                            if(pChild3->Attribute("input5"))
1506                                mList[mission_num].services[conditional_2].input[4] = pChild3->Attribute("input5");
1507                            if(pChild3->Attribute("output1"))
1508                                mList[mission_num].services[conditional_2].output[0] = pChild3->Attribute("output1");
1509                            if(pChild3->Attribute("output2"))
1510                                mList[mission_num].services[conditional_2].output[1] = pChild3->Attribute("output2");
1511                            if(pChild3->Attribute("output3"))
1512                                mList[mission_num].services[conditional_2].output[2] = pChild3->Attribute("output3");
1513                            if(pChild3->Attribute("output4"))
1514                                mList[mission_num].services[conditional_2].output[3] = pChild3->Attribute("output4");
1515                            if(pChild3->Attribute("output5"))
1516                                mList[mission_num].services[conditional_2].output[4] = pChild3->Attribute("output5");
1517                        mList[mission_num].services[conditional_2].num_conds = cond_array[2];
1518                        cond_array[1]+=cond_array[2]+1;
1519                        //printf("cond_array[2]%d\n", cond_array[2]);
1520                        cond_array[2] = 0;
1521
1522
1523                }
1524                if(!strcmp(pChild2->Value(), "shell") || conditional_1 != service_num) {
1525                    mList[mission_num].services[conditional_1].name = pChild2->Value();
1526                }
1527                else{
1528                    mList[mission_num].services[service_num].name = pChild2->Attribute("name");
1529                }
1530                if(pChild2->Attribute("input1"))
1531                    mList[mission_num].services[conditional_1].input[0] = pChild2->Attribute("input1");
1532                if(pChild2->Attribute("input2"))
1533                    mList[mission_num].services[conditional_1].input[1] = pChild2->Attribute("input2");
1534                    if(pChild2->Attribute("input3"))
1535                        mList[mission_num].services[conditional_1].input[2] = pChild2->Attribute("input3");
1536                    if(pChild2->Attribute("input4"))
1537                        mList[mission_num].services[conditional_1].input[3] = pChild2->Attribute("input4");
1538                    if(pChild2->Attribute("input5"))
1539                        mList[mission_num].services[conditional_1].input[4] = pChild2->Attribute("input5");
1540                    if(pChild2->Attribute("output1"))
1541                        mList[mission_num].services[conditional_1].output[0] = pChild2->Attribute("output1");
1542                    if(pChild2->Attribute("output2"))
1543                        mList[mission_num].services[conditional_1].output[1] = pChild2->Attribute("output2");
1544                    if(pChild2->Attribute("output3"))
1545                        mList[mission_num].services[conditional_1].output[2] = pChild2->Attribute("output3");
1546                    if(pChild2->Attribute("output4"))
1547                        mList[mission_num].services[conditional_1].output[3] = pChild2->Attribute("output4");
1548                    if(pChild2->Attribute("output5"))
1549                        mList[mission_num].services[conditional_1].output[4] = pChild2->Attribute("output5");
1550
1551                mList[mission_num].services[conditional_1].num_conds = cond_array[1];
1552                cond_array[0]+=cond_array[1]+1;
1553                //printf("cond_array[1]%d\n", cond_array[1]);
1554                cond_array[1] = 0;
1555            }
1556           
1557            if(!strcmp(pChild1->Value(), "shell") || conditional_0 != service_num) {
1558                mList[mission_num].services[conditional_0].name = pChild1->Value();
1559            }
1560            else{
1561                mList[mission_num].services[conditional_0].name = pChild1->Attribute("name");
1562            }
1563                //printf("name=%s\n", mList[mission_num].services[conditional_0].name.c_str());
1564                if(pChild1->Attribute("input1"))
1565                    mList[mission_num].services[conditional_0].input[0] = pChild1->Attribute("input1");
1566                if(pChild1->Attribute("input2"))
1567                    mList[mission_num].services[conditional_0].input[1] = pChild1->Attribute("input2");
1568                if(pChild1->Attribute("input3"))
1569                    mList[mission_num].services[conditional_0].input[2] = pChild1->Attribute("input3");
1570                if(pChild1->Attribute("input4"))
1571                    mList[mission_num].services[conditional_0].input[3] = pChild1->Attribute("input4");
1572                if(pChild1->Attribute("input5"))
1573                    mList[mission_num].services[conditional_0].input[4] = pChild1->Attribute("input5");
1574                if(pChild1->Attribute("output1"))
1575                    mList[mission_num].services[conditional_0].output[0] = pChild1->Attribute("output1");
1576                if(pChild1->Attribute("output2"))
1577                    mList[mission_num].services[conditional_0].output[1] = pChild1->Attribute("output2");
1578                if(pChild1->Attribute("output3"))
1579                    mList[mission_num].services[conditional_0].output[2] = pChild1->Attribute("output3");
1580                if(pChild1->Attribute("output4"))
1581                    mList[mission_num].services[conditional_0].output[3] = pChild1->Attribute("output4");
1582                if(pChild1->Attribute("output5"))
1583                    mList[mission_num].services[service_num].output[4] = pChild1->Attribute("output4");
1584            mList[mission_num].services[conditional_0].num_conds = cond_array[0];
1585            cond_array[0] = 0;
1586            service_num++;
1587        }
1588        //for(int i = 0; i < service_num; i++)
1589         //printf("ttt%d\n", mList[mission_num].services[i].num_conds);
1590       
1591        mList[mission_num].numServices = service_num;
1592        mList[mission_num].name = pChild0->Attribute("name");
1593        mList[mission_num].missionID = atoi(pChild0->Attribute("id"));
1594        if(pChild0->Attribute("input1"))
1595            mList[mission_num].input[0] = pChild0->Attribute("input1");
1596        if(pChild0->Attribute("input2"))
1597            mList[mission_num].input[1] = pChild0->Attribute("input2");
1598        if(pChild0->Attribute("input3"))
1599            mList[mission_num].input[2] = pChild0->Attribute("input3");
1600        if(pChild0->Attribute("input4"))
1601            mList[mission_num].input[3] = pChild0->Attribute("input4");
1602        if(pChild0->Attribute("input5"))
1603            mList[mission_num].input[4] = pChild0->Attribute("input4");
1604        if(pChild0->Attribute("output1"))
1605            mList[mission_num].output[0] = pChild0->Attribute("output1");
1606        if(pChild0->Attribute("output2"))
1607            mList[mission_num].output[1] = pChild0->Attribute("output2");
1608        if(pChild0->Attribute("output3"))
1609            mList[mission_num].output[2] = pChild0->Attribute("output3");
1610        if(pChild0->Attribute("output4"))
1611            mList[mission_num].output[3] = pChild0->Attribute("output4");
1612        if(pChild0->Attribute("output5"))
1613            mList[mission_num].output[4] = pChild0->Attribute("output5");
1614        //printf("mis, input1=%s, output1=%s\n", mList[mission_num].input[0].c_str(), mList[mission_num].output[0].c_str());
1615        //printf("NUMSERVICES = %d\n", mList[mission_num].numServices);
1616        mission_num++;
1617    }
1618}
1619
1620/* CALLED BY: MessageHandler
1621 * INPUTS: |ID| The ID number of the engine to be registered
1622 * OUTPUTS: <none>
1623 *
1624 * DESCRIPTION: Sends a registration message onto the shell and sends the ACK back to the component
1625 */
1626void
1627ServiceManagementLayer::RegisterCognitiveEngine(int32_t ID)
1628{
1629    //LOG("SML::regcogeng");
1630    SendMessage(shellSocketFD, "register_engine_cognitive");
1631
1632   // printf("SSFD = %d\n", shellSocketFD);
1633    LOG("ServiceManagementLayer:: CE registration message forwarded to shell.\n");
1634    char buffer[256];
1635    memset(buffer, 0, 256);
1636    ReadMessage(shellSocketFD, buffer);
1637    //printf("ServiceManagementLayer::buffer = %s\n", buffer);
1638    SendMessage(CE_List[ID].FD, buffer);
1639
1640    TransferRadioConfiguration(ID);
1641    memset(buffer, 0, 256);
1642    //printf("start trans exp\n");
1643    TransferExperience(ID);
1644    memset(buffer, 0, 256);
1645    numberOfCognitiveEngines++;
1646    CE_Present = true;
1647    //printf("done registering CE!\n");
1648}
1649
1650/* CALLED BY: MessageHandler
1651 * INPUTS: |ID| The ID number of the engine to have it's services deregistered
1652 * OUTPUTS: <none>
1653 *
1654 * DESCRIPTION: Deletes individual services from the DB
1655 * NOTE THAT this function only needs to be called if service deregistration is going
1656 * to be done at a different time than component deregistration; it is handled
1657 * more efficiently and directly during that deregistration process.
1658 */
1659void
1660ServiceManagementLayer::DeregisterServices(int32_t ID)
1661{
1662    char buffer[256];
1663    memset(buffer, 0, 256);
1664    ReadMessage(CE_List[ID].FD, buffer);
1665    strcpy(_services_DB->command, "DELETE FROM ");
1666    strcat(_services_DB->command, _services_DB->tablename);
1667    strcat(_services_DB->command, " WHERE ID_Num IN (SELECT");
1668    sprintf(_services_DB->command, " %s %d",_services_DB->command, ID);
1669    strcat(_services_DB->command, " FROM ");
1670    strcat(_services_DB->command, _services_DB->tablename);
1671    strcat(_services_DB->command, " WHERE Service_Name");
1672    strcat(_services_DB->command, "==");
1673    sprintf(_services_DB->command, "%s'%s');", _services_DB->command, buffer);
1674    char *errorMsg;
1675    int rc = sqlite3_exec(_services_DB->db, _services_DB->command, callback, 0, &errorMsg);
1676    if( rc!=SQLITE_OK && rc!=101 )
1677        fprintf(stderr, "SQL error: %s\n", errorMsg);
1678}
1679
1680/* CALLED BY: MessageHandler
1681 * INPUTS: |ID| The ID number of the engine to have it's services deregistered
1682 * OUTPUTS: <none>
1683 *
1684 * DESCRIPTION: Deletes the contact info for the cognitive engine, forwards a deregistration message to the shell
1685 * Also, deletes the services from the DB
1686 */
1687void
1688ServiceManagementLayer::DeregisterCognitiveEngine(int32_t ID)
1689{
1690    LOG("ServiceManagementLayer:: CE deregistration message forwarded to shell.\n");
1691
1692    numberOfCognitiveEngines--;
1693    if(numberOfCognitiveEngines == 0)
1694        CE_Present = false;
1695
1696    SendMessage(shellSocketFD, "deregister_engine_cognitive");
1697    char buffer[256];
1698    memset(buffer, 0, 256);
1699    ReadMessage(shellSocketFD, buffer);
1700    SendMessage(CE_List[ID].FD, buffer);
1701    if(strcmp("deregister_ack", buffer) != 0) {
1702        ERROR(1, "SML:: Failed to close CE socket\n");
1703    }
1704
1705    //Deregister the services
1706    strcpy(_services_DB->command, "DELETE FROM ");
1707    strcat(_services_DB->command, _services_DB->tablename);
1708    strcat(_services_DB->command, " WHERE ");
1709    strcat(_services_DB->command, "ID_Num");
1710    strcat(_services_DB->command, "==");
1711    sprintf(_services_DB->command, "%s%d;", _services_DB->command, ID);
1712    char *errorMsg;
1713    int rc = sqlite3_exec(_services_DB->db, _services_DB->command, callback, 0, &errorMsg);
1714    if( rc!=SQLITE_OK && rc!=101 )
1715        fprintf(stderr, "SQL error: %s\n", errorMsg);
1716
1717
1718    CE_List[ID].FD = -1;
1719    CE_List[ID].ID_num = -1;
1720
1721    LOG("Cognitive Radio Shell:: CE Socket closed for engine #%d.\n", ID);
1722}
1723
1724
1725/* CALLED BY: test class
1726 * INPUTS: <none>
1727 * OUTPUTS: <none>
1728 *
1729 * DESCRIPTION: Sets up a server socket and listens for communication on either that or the shell socket
1730 */
1731void
1732ServiceManagementLayer::StartSMLServer()
1733{
1734    //printf("Ready for CE Signal! (registration done)\n");
1735    struct timeval selTimeout;
1736    int32_t running = 1;
1737    int32_t port, rc, new_sd = 1;
1738    int32_t desc_ready = 1;
1739                //If there is, call the MessageHandler with the Shell_Msg code of -1
1740    fd_set sockSet, shellSet;
1741
1742    cogEngSrv = CreateTCPServerSocket(SMLport);
1743    int32_t maxDescriptor = cogEngSrv;
1744
1745    if(InitializeTCPServerPort(cogEngSrv) == -1)
1746        ERROR(1,"Error initializing primary port\n");
1747
1748    int i = 10000000;  //TODO change to "running" if endpoint can be reached
1749    while (running) {
1750        i--;
1751        /* Zero socket descriptor vector and set for server sockets */
1752        /* This must be reset every time select() is called */
1753        FD_ZERO(&sockSet);
1754        FD_SET(cogEngSrv, &sockSet);
1755        for(uint16_t k = 0; k < Current_ID; k++){
1756            if(CE_List[k].ID_num != -1)
1757                FD_SET(CE_List[k].FD, &sockSet);
1758        }
1759            //printf("k=%d, CID=%d\n", k, CE_List[k].FD);
1760
1761        /* Timeout specification */
1762        /* This must be reset every time select() is called */
1763        selTimeout.tv_sec = 0;       /* timeout (secs.) */
1764        selTimeout.tv_usec = 0;            /* 0 microseconds */
1765        //Changed both to zero so that select will check messages from the shell instead of blocking
1766        //when there is no command from the CE's to be processed
1767
1768        //Check if there is a message on the socket waiting to be read
1769        rc = select(maxDescriptor + 1, &sockSet, NULL, NULL, &selTimeout);
1770        //printf("rc=%d\n", rc);
1771        if(rc == 0){
1772            //LOG("No echo requests for %i secs...Server still alive\n", timeout);
1773       
1774            FD_ZERO(&shellSet);
1775            FD_SET(shellSocketFD, &shellSet);
1776            selTimeout.tv_sec = 0;
1777            selTimeout.tv_usec = 0;
1778            //Check if there is a message on the shell socket ready to be processed
1779            select(shellSocketFD + 1, &shellSet, NULL, NULL, &selTimeout);
1780            //printf("rc2=%d\n", rc2);
1781                //If there is, call the MessageHandler with the Shell_Msg code of -1
1782            if(FD_ISSET(shellSocketFD, &shellSet)){
1783                //printf("shell_msg, %d\n", rc2);
1784                MessageHandler(-1);}
1785        }
1786        else {
1787            desc_ready = rc;
1788            for(port = 0; port <= maxDescriptor && desc_ready > 0; port++) {
1789                if(FD_ISSET(port, &sockSet)) {
1790                    desc_ready -= 1;
1791
1792                    //Check if request is new or on an existing open descriptor
1793                    if(port == cogEngSrv) {
1794                        //If new, assign it a descriptor and give it an ID
1795                        new_sd = AcceptTCPConnection(port);
1796                         
1797                        if(new_sd < 0)
1798                            break;
1799
1800                        CE_List[Current_ID].FD = new_sd;
1801                        CE_List[Current_ID].ID_num = Current_ID;
1802                        MessageHandler(Current_ID);
1803                        Current_ID++;
1804       
1805                        FD_SET(new_sd,&sockSet);
1806                        if(new_sd > maxDescriptor)
1807                           maxDescriptor = new_sd;
1808                    }
1809                    else {
1810                        //If old, figure out which ID it coresponds to and handle it accordingly
1811                        for(uint16_t z = 0; z < Current_ID; z++)
1812                        {
1813                                if(CE_List[z].FD == port){
1814                                        MessageHandler(z);}
1815                        }
1816                    }
1817                }
1818            }
1819        }
1820    }       
1821
1822    /* Close sockets */
1823    close(cogEngSrv);
1824
1825    //delete &cogEngSrv;
1826    return;
1827}
Note: See TracBrowser for help on using the browser.