diff eventLogger.mm @ 30:c0a6f7c66719

Josh M test "in house" version 0.1
author Robert Tubb <rt300@eecs.qmul.ac.uk>
date Wed, 27 Feb 2013 11:39:07 +0000
parents fabb3a5cdfc9
children 23ef179c3748
line wrap: on
line diff
--- a/eventLogger.mm	Fri Feb 22 17:41:38 2013 +0000
+++ b/eventLogger.mm	Wed Feb 27 11:39:07 2013 +0000
@@ -35,26 +35,129 @@
 
 void EventLogger::init(){
     
-    readJsonToLog(ofxiPhoneGetDocumentsDirectory() + EVENT_LOG_FILENAME);
+    checkExistingLogFile(ofxiPhoneGetDocumentsDirectory() + EVENT_LOG_FILENAME);
     sessionStartTime = ofGetSystemTime();
     
     testConnection();
 
     logEvent(APP_STARTED);
 
-    stringstream r;
-    r << LOGGING_SERVER_URL << "testConnection?jsontext=" << "{\"test\":\"test\"}&Content-Length=456";
+    NSString *jsondata;
+    jsondata=@"{\"test\":\"test\"";
+    serverComms = [[ServerComms alloc] init];
 
-    NSString *urlstring;
-    urlstring = @"http://127.0.0.1:8080/testservice/testConnection?jsontext={\"objc post\":\"obj c post\"}";
-    serverComms = [[ServerComms alloc] init];
-    [serverComms postRequest:urlstring];
+}
+//---------------------------------------------------------------------------
+// this reads the persistent log file , checks if we've used the app before and
+// if we've answered questionnaire or not
+void EventLogger::checkExistingLogFile(const string &jsonFile){
+    Json::Value root;
+    Json::Reader reader;
+    
+    /////////////
+    // read file
+    
+    ifstream theFile(jsonFile.c_str());
+    stringstream fileText;
+    string line;
+    if(!theFile){
+        
+        firstEverAppOpen();
+        return;
+    }else{
+        while(theFile){
+            theFile >> line;
+            // cout << line;  // lots!!!!
+            fileText << line;
+        }
+        theFile.close();
+    }
+    
+    // otherwise, we've been in here before
+    
+    /////////////
+    // Parse json
+    cout << "size of log JSON string:" << fileText.str().length() << "BYTES \n";
+    
+    bool parsingSuccessful = reader.parse( fileText.str(), root );
+    
+    if ( !parsingSuccessful )
+    {
+        // report to the user the failure and their locations in the document.
+        std::cout  << "Failed to parse event log JSON: \n"
+        << reader.getFormattedErrorMessages();
+        return;
+    }
+    
+    /////////////////
+    // now put user deets into variables
+    
+    userName = root["userName"].asString();
+    deviceID = root["deviceID"].asLargestInt();
+    nextUploadNumber = root["uploadNumber"].asInt();
+    savedInteractionTime = root["savedInteractionTime"].asLargestInt();
+    questionnaireCompleted = root["questionnaireCompleted"].asBool();
+    questionnaireUploaded = root["questionnaireUploaded"].asBool();
+    interfaceOrder = root["interfaceOrder"].asInt();
+    
 
+    // check for unuploaded evts
+    const Json::Value jlogs = root["events"];
     
-    urlstring = nil;
+    for ( int index = 0; index < jlogs.size(); ++index ) theEvents.push_back(lEvent(jlogs[index]));
+    if(theEvents.size() > nextUploadQty && ! logUploadInProgress){
+        //try to upload
+        uploadEventLog(true);
+    }
+    
+    //////////////
+    // what stage is the experiment at??
+    
+    if(questionnaireCompleted && !questionnaireUploaded){
+        // then read it in and upload it
+        Json::Value JQ = root["questionnaire"];
+        Json::Value JArray = JQ["qAnswers"];
+        if(JArray.size() < 2){
+            cout << "Error - status of questionnaire is wierd\n";
+        }
+        for ( unsigned int i = 0; i < JArray.size(); i++ )
+        {
+            questionnaireAnswers.push_back(JArray[i].asInt());
+        }
+        questionnaireComments = JQ["comments"].toStyledString();
+        uploadQuestionnaire();
+    }
+    //TODO if questionnaire wasn't reached but still opened then set the timer to something sensible
+    
+    if(!questionnaireCompleted){
+        // for now sod it, start from scratch
+        firstEverAppOpen();
+        return;
+    }
+    cout << "Total interaction time: " << savedInteractionTime << '\n';
+    
+    //timer.setInteractionTime(savedInteractionTime);
+    //timer.setOrderFromPrevious(interfaceOrder);
+    
 }
 
 //---------------------------------------------------------------------------
+
+void EventLogger::firstEverAppOpen(){
+    cout<<"no event log file - first APP open\n";
+    nextUploadNumber = 0;
+    deviceID = ofGetSystemTimeMicros();
+    savedInteractionTime = 0;
+    questionnaireCompleted = false;
+    questionnaireUploaded = false;
+    
+    ((testApp *)ofGetAppPtr())->showIntro();
+    consentGiven = false;
+    
+}
+
+
+//---------------------------------------------------------------------------
 void EventLogger::questionnaireAnswersObtained(vector<int> answers, const char* userComments){
     
     questionnaireCompleted = true;
@@ -73,19 +176,7 @@
 }
 //---------------------------------------------------------------------------
 bool EventLogger::sendToServer(string functionName, Json::Value jsonData, bool async = false){
-    bool sent;
-    stringstream request;
 
-    request << LOGGING_SERVER_URL << functionName << "?jsontext=";
-    /*
-    if(functionName == "testConnection"){
-         request = "http://127.0.0.1:8080/testservice/testConnection?jsontext=";
-    }else if(functionName == "questionnaire"){
-         request = "http://127.0.0.1:8080/testservice/questionnaire?jsontext=";
-    }else if(functionName == "eventlog"){
-         request = "http://127.0.0.1:8080/testservice/eventlog?jsontext=";
-    }
-     */
     Json::FastWriter writer;
     string jsontext = writer.write( jsonData );
     
@@ -93,48 +184,53 @@
     if (!jsontext.empty() && jsontext[jsontext.length()-1] == '\n') {
         jsontext.erase(jsontext.length()-1);
     }
+    ostringstream jd;
+    jd << jsontext;
+    NSString *theData = [NSString stringWithUTF8String:jd.str().c_str()];
+    NSString *theType = [NSString stringWithUTF8String:functionName.c_str()];
 
-    request << jsontext;
+    if(async){
+        [serverComms doPostRequest:theType withData:theData];
+    }else{
+        bool success = [serverComms doSyncPostRequest:theType withData:theData];
+        return success;
+    }
     
-    cout << request.str();
-    
-    if(!async){
-        ofURLFileLoader fileLoader;
-        ofHttpResponse resp;
-        resp = fileLoader.get(request.str());
-
-        cout << "HTTP STATUS  " << resp.status << "\n";
-        cout << "HTTP ERROR  " << resp.error << "\n";
-        cout << "HTTP DATA  " << resp.data << "\n"; // ofBuffer
-        
-        stringstream response;
-        response << resp.data;
-        
-        if (resp.status == 200){
-            if(response.str() == "OK"){
-                
-                sent = true;
-            }else{
-                // not ok
-                // problem serverside
-                sent = false;
-            }
-        }else{
-            
-            sent = false;
-            // SHOW AN ALERT TO USER?
-        }
-        
-        return sent;
-    }else{ // async
-        ofURLFileLoader fileLoader;
-        currentHTTPRequestID = ofLoadURLAsync(request.str(), functionName);
-        ofRegisterURLNotification(this);
-        
-        return true; // ???
-    }
 }
 //-----------------------------
+void EventLogger::questionnaireOK(){
+    questionnaireUploaded = true;
+}
+//-----------------------------
+void EventLogger::eventlogOK(){
+    //theEvents.clear();
+    cout << "EVENT LOG UPLOAD SUCCESS\n";
+    nextUploadNumber++;
+    logUploadInProgress = false;
+}
+//-----------------------------
+void EventLogger::testConnectionOK(){
+    cout << "^^^^^^^^ server connection OK ^^^^^^^^ \n";
+    serverConnectionOK = true;
+}
+//-----------------------------
+void EventLogger::questionnaireNotOK(){
+    questionnaireUploaded = false;
+}
+//-----------------------------
+void EventLogger::eventlogNotOK(){
+    // try later
+    nextUploadQty += UPLOAD_CHUNK_SIZE;
+    logUploadInProgress = false;
+}
+//-----------------------------
+void EventLogger::testConnectionNotOK(){
+    cout << "^^^^^^^^ server connection NOT OK ^^^^^^^^ \n";
+    serverConnectionOK = false;
+    // alert?
+    
+}
+/*
 void EventLogger::urlResponse(ofHttpResponse & response){
     cout << "gotHTTPRequestStatus\n";
     cout << "HTTP REQUEST NAME  " << response.request.name << "\n";
@@ -192,94 +288,15 @@
     }
 
 }
+ */
 //---------------------------------------------------------------------------
 bool EventLogger::testConnection(){
     Json::Value root;
-    root["x"] = "y";
-    
-    
+    root["test"] = "test";
     sendToServer("testConnection", root, true);
 
 }
 //---------------------------------------------------------------------------
-// this reads the persistent log file , checks if we've used the app before and
-// if we've answered questionnaire or not
-void EventLogger::readJsonToLog(const string &jsonFile){
-    Json::Value root;
-    Json::Reader reader;
-    
-    
-    ifstream theFile(jsonFile.c_str());
-    stringstream fileText;
-    string line;
-    if(!theFile){
-        
-        firstEverAppOpen();
-        
-        return;
-    }else{
-        while(theFile){
-            theFile >> line;
-            // cout << line;  // lots!!!!
-            fileText << line;
-        }
-        theFile.close();
-    }
-    
-    cout << "size of log JSON string:" << fileText.str().length() << "BYTES \n";
-    
-    bool parsingSuccessful = reader.parse( fileText.str(), root );
-    
-    if ( !parsingSuccessful )
-    {
-        // report to the user the failure and their locations in the document.
-        std::cout  << "Failed to parse event log JSON: \n"
-        << reader.getFormattedErrorMessages();
-        return;
-    }
-    
-    // now put user deets into variables
-    userName = root["userName"].asString();
-    deviceID = root["deviceID"].asLargestInt();
-    nextUploadNumber = root["uploadNumber"].asInt();
-    savedInteractionTime = root["savedInteractionTime"].asLargestInt();
-    questionnaireCompleted = root["questionnaireCompleted"].asBool();
-    questionnaireUploaded = root["questionnaireUploaded"].asBool();
-    interfaceOrder = root["interfaceOrder"].asInt();
-    
-    if(questionnaireCompleted && !questionnaireUploaded){
-        // then read it in and upload it
-        Json::Value JQ = root["questionnaire"];
-        Json::Value JArray = JQ["qAnswers"];
-        if(JArray.size() < 2){
-            cout << "Error - status of questionnaire is wierd\n";
-        }
-        for ( unsigned int i = 0; i < JArray.size(); i++ )
-        {
-            questionnaireAnswers.push_back(JArray[i].asInt());
-        }
-        questionnaireComments = JQ["comments"].toStyledString();
-        uploadQuestionnaire();
-    }
-    
-    // check for unuploaded evts
-    const Json::Value jlogs = root["events"];
-    
-    for ( int index = 0; index < jlogs.size(); ++index ) theEvents.push_back(lEvent(jlogs[index]));
-    if(theEvents.size() > nextUploadQty && ! logUploadInProgress){
-        //try to upload
-        uploadEventLog(true);
-    }
-    // TODO if the total interaction time is greater than a certain amount && no questions answered - questionnaire time!
-    cout << "Total interaction time: " << savedInteractionTime << '\n';
-    
-    //timer.setInteractionTime(savedInteractionTime);
-    //timer.setOrderFromPrevious(interfaceOrder);
-    
-}
-
-
-//---------------------------------------------------------------------------
 
 bool EventLogger::uploadEventLog(bool async){
 
@@ -294,7 +311,7 @@
         }else{
             
             // if success - clear memory
-            theEvents.clear();
+            //theEvents.clear();
             cout << "UPLOAD SUCCESS\n";
             nextUploadNumber++;
         }
@@ -309,20 +326,7 @@
 //----------------------------------------------------------------------------
 //void EventLogger::deleteLogFile(){
 
-//---------------------------------------------------------------------------
 
-void EventLogger::firstEverAppOpen(){
-    cout<<"no event log file - first APP open\n";
-    nextUploadNumber = 0;
-    deviceID = ofGetSystemTimeMicros();
-    savedInteractionTime = 0;
-    questionnaireCompleted = false;
-    questionnaireUploaded = false;
-    
-    ((testApp *)ofGetAppPtr())->showIntro();
-    consentGiven = false;
-    
-}
 //---------------------------------------------------------------------------
 // only called when doing supervised tests
 void EventLogger::newUser(){
@@ -492,9 +496,8 @@
     root["savedInteractionTime"] = savedInteractionTime;
     root["questionnaireCompleted"] = questionnaireCompleted;
     root["questionnaireUploaded"] = questionnaireUploaded;
-    if(questionnaireCompleted && !questionnaireUploaded){
-        root["questionnaire"] = questionnaireToJson();
-    }
+    root["questionnaire"] = questionnaireToJson();
+
     
     int i = 0;
     for(eventIter = theEvents.begin(); eventIter < theEvents.end(); eventIter++){
@@ -520,7 +523,6 @@
         questionnaire[i] = (*aIter);
         i++;
     }
-    cout << questionnaireComments << "\n";
 
     root["qAnswers"] = questionnaire;
     root["comments"] = questionnaireComments;
@@ -531,6 +533,13 @@
     
     return root;
 }
+
 //---------------------------------------------------------------------------
+void EventLogger::printAll(){
+    cout << "-----------------ALL LOGGED EVENTS----------------- \n";
+    vector<lEvent>::iterator evIter;
+    cout << logsToJson() << "\n";
+    cout << "---------------------QUESTIONNAIRE---------------- \n";
+    cout << questionnaireToJson() << "\n";
+};
 //---------------------------------------------------------------------------
-//---------------------------------------------------------------------------