Avnet AT&T IoT Starter Kit demo for Pubnub

Dependencies:   FXOS8700CQ mbed

Revision:
35:d0d86a2bcdb3
Parent:
34:029e07b67a41
--- a/main.cpp	Sat Jul 23 01:10:53 2016 +0000
+++ b/main.cpp	Tue Aug 30 22:02:03 2016 +0000
@@ -8,6 +8,9 @@
 #include "sensors.h"
 
 #include "hardware.h"
+
+#include "pubnub.h"
+
 I2C i2c(PTC11, PTC10);    //SDA, SCL -- define the I2C pins being used
 
 // comment out the following line if color is not supported on the terminal
@@ -36,7 +39,7 @@
 
 #define MDM_DBG_OFF                             0
 #define MDM_DBG_AT_CMDS                         (1 << 0)
-int mdm_dbgmask = MDM_DBG_OFF;
+int mdm_dbgmask = MDM_DBG_AT_CMDS;
 
 Serial         pc(USBTX, USBRX);
 SerialBuffered mdm(PTD3, PTD2, 128);
@@ -187,7 +190,7 @@
     size_t n = strlen(cmd);
     if (cmd && n > 0) {
         if (mdm_dbgmask & MDM_DBG_AT_CMDS) {
-            printf(MAG "ATCMD: " DEF "--> " GRN "%s" DEF "\n", cmd);
+            pc.printf(MAG "ATCMD: " DEF "--> " GRN "%s" DEF "\n", cmd);
         }
         while (n--) {
             mdm.putc(*cmd++);
@@ -210,15 +213,17 @@
             if (lenCmd == 0)
                 continue;
 
-            if (lenCmd < 0)
+            if (lenCmd < 0) {
+                pc.printf(RED "MDM_ERR_TIMEOUT, lenCmd = %d" DEF, lenCmd);
                 return MDM_ERR_TIMEOUT;
+            }
             else {
                 *len += lenCmd;
                 *rsp += cmd_buf;
             }
 
             if (mdm_dbgmask & MDM_DBG_AT_CMDS) {
-                printf(MAG "ATRSP: " DEF "<-- " CYN "%s" DEF "\n", cmd_buf);
+                //pc.printf(MAG "ATRSP: " DEF "<-- " CYN "%s" DEF "\n", cmd_buf);
             }
 
             int rsp_idx = 0;
@@ -229,6 +234,7 @@
                 rsp_idx++;
             }
         }
+        pc.printf(RED "MDM_ERR_TIMEOUT, 'ali stvarno'" DEF);
         return MDM_ERR_TIMEOUT;
     }
     pc.printf("D %s",rsp);
@@ -275,33 +281,7 @@
     .Humidity_Si7020    = "0"
 };
 
-void GenerateModemString(char * modem_string)
-{
-    switch(iSensorsToReport)
-    {
-        case TEMP_HUMIDITY_ONLY:
-        {
-            sprintf(modem_string, "GET %s%s?serial=%s&temp=%s&humidity=%s %s%s\r\n\r\n", FLOW_BASE_URL, FLOW_INPUT_NAME, FLOW_DEVICE_NAME, SENSOR_DATA.Temperature, SENSOR_DATA.Humidity, FLOW_URL_TYPE, MY_SERVER_URL);
-            break;
-        }
-        case TEMP_HUMIDITY_ACCELEROMETER:
-        {
-            sprintf(modem_string, "GET %s%s?serial=%s&temp=%s&humidity=%s&accelX=%s&accelY=%s&accelZ=%s %s%s\r\n\r\n", FLOW_BASE_URL, FLOW_INPUT_NAME, FLOW_DEVICE_NAME, SENSOR_DATA.Temperature, SENSOR_DATA.Humidity, SENSOR_DATA.AccelX,SENSOR_DATA.AccelY,SENSOR_DATA.AccelZ, FLOW_URL_TYPE, MY_SERVER_URL);
-            break;
-        }
-        case TEMP_HUMIDITY_ACCELEROMETER_PMODSENSORS:
-        {
-            sprintf(modem_string, "GET %s%s?serial=%s&temp=%s&humidity=%s&accelX=%s&accelY=%s&accelZ=%s&proximity=%s&light_uv=%s&light_vis=%s&light_ir=%s %s%s\r\n\r\n", FLOW_BASE_URL, FLOW_INPUT_NAME, FLOW_DEVICE_NAME, SENSOR_DATA.Temperature, SENSOR_DATA.Humidity, SENSOR_DATA.AccelX,SENSOR_DATA.AccelY,SENSOR_DATA.AccelZ, SENSOR_DATA.Proximity, SENSOR_DATA.UVindex, SENSOR_DATA.AmbientLightVis, SENSOR_DATA.AmbientLightIr, FLOW_URL_TYPE, MY_SERVER_URL);
-            break;
-        }
-        default:
-        {
-            sprintf(modem_string, "Invalid sensor selected\r\n\r\n");
-            break;
-        }
-    } //switch(iSensorsToReport)
-} //GenerateModemString        
-            
+           
             
 //Periodic timer
 Ticker OneMsTicker;
@@ -332,43 +312,10 @@
     led_blue = !(ucColor & 0x4); //bit 2
 } //SetLedColor()
 
-//********************************************************************************************************************************************
-//* Process JSON response messages
-//********************************************************************************************************************************************
-bool extract_JSON(char* search_field, char* found_string)
+
+bool parse_JSON(char const* json_string)
 {
-    char* beginquote;
-    char* endquote;
-    beginquote = strchr(search_field, '{'); //start of JSON
-    endquote = strchr(search_field, '}'); //end of JSON
-    if (beginquote != 0)
-    {
-        uint16_t ifoundlen;
-        if (endquote != 0)
-        {
-            ifoundlen = (uint16_t) (endquote - beginquote) + 1;
-            strncpy(found_string, beginquote, ifoundlen );
-            found_string[ifoundlen] = 0; //null terminate
-            return true;
-        }
-        else
-        {
-            endquote = strchr(search_field, '\0'); //end of string...  sometimes the end bracket is missing
-            ifoundlen = (uint16_t) (endquote - beginquote) + 1;
-            strncpy(found_string, beginquote, ifoundlen );
-            found_string[ifoundlen] = 0; //null terminate
-            return false;
-        }
-    }
-    else
-    {
-        return false;
-    }
-} //extract_JSON
-
-bool parse_JSON(char* json_string)
-{
-    char* beginquote;
+    char const* beginquote;
     char token[] = "\"LED\":\"";
     beginquote = strstr(json_string, token );
     if ((beginquote != 0))
@@ -430,7 +377,71 @@
     }
 } //parse_JSON
 
-int main() {
+
+static void GeneratePubnubJSON(char *s, unsigned n)
+{
+    switch(iSensorsToReport)
+    {
+    case TEMP_HUMIDITY_ONLY:
+    {
+        snprintf(s, n, "{\"serial\":\"%s\",\"temp\":%s,\"humidity\":%s}", FLOW_DEVICE_NAME, SENSOR_DATA.Temperature, SENSOR_DATA.Humidity);
+        break;
+    }
+    case TEMP_HUMIDITY_ACCELEROMETER:
+    {
+        snprintf(s, n, "{\"serial\":\"%s\",\"temp\":%s,\"humidity\":%s,\"accelX\":%s,\"accelY\":%s,\"accelZ\":%s}", FLOW_DEVICE_NAME, SENSOR_DATA.Temperature, SENSOR_DATA.Humidity, SENSOR_DATA.AccelX, SENSOR_DATA.AccelY, SENSOR_DATA.AccelZ);
+        break;
+    }
+    case TEMP_HUMIDITY_ACCELEROMETER_PMODSENSORS:
+    {
+        snprintf(s, n, "{\"serial\":\"%s\",\"temp\":%s,\"humidity\":%s,\"accelX\":%s,\"accelY\":%s,\"accelZ\":%s,\"proximity\":%s,\"light_uv\":%s,\"light_vis\":%s,\"light_ir\":%s}", FLOW_DEVICE_NAME, SENSOR_DATA.Temperature, SENSOR_DATA.Humidity, SENSOR_DATA.AccelX,SENSOR_DATA.AccelY,SENSOR_DATA.AccelZ, SENSOR_DATA.Proximity, SENSOR_DATA.UVindex, SENSOR_DATA.AmbientLightVis, SENSOR_DATA.AmbientLightIr);
+        break;
+    }
+    default:
+    {
+        snprintf(s, n, "\"Invalid sensor selected\"");
+        break;
+    }
+    } //switch(iSensorsToReport)
+}
+
+
+static void print_pubnub_result(pubnub_ctx::result r)
+{
+    switch (r) {
+    case pubnub_ctx::format_error:
+        pc.printf(RED "Pubnub response format error" DEF "\r\n");
+        break;
+    case pubnub_ctx::response_too_short:
+        pc.printf(RED "Pubnub response too short" DEF "\r\n");
+        break;
+    case pubnub_ctx::missing_open_bracket:
+        pc.printf(RED "Pubnub response missing open bracket `[`" DEF "\r\n");
+        break;
+    case pubnub_ctx::missing_close_bracket:
+        pc.printf(RED "Pubnub response missing close bracket `]`" DEF "\r\n");
+        break;
+    case pubnub_ctx::missing_time_token:
+        pc.printf(RED "Pubnub subscribe response missing time token" DEF "\r\n");
+        break;
+    case pubnub_ctx::bad_time_token:
+        pc.printf(RED "Pubnub subscribe response bad time token" DEF "\r\n");
+        break;
+    case pubnub_ctx::publish_failed:
+        pc.printf(RED "Pubnub publish failed" DEF "\r\n");
+        break;
+    case pubnub_ctx::ok:
+        pc.printf(GRN "Pubnub transaction success" DEF "\r\n");
+        break;
+    default:
+        pc.printf(RED "Unknown Pubnub erorr %d" DEF "\r\n", static_cast<int>(r));
+        break;
+    }
+}
+
+
+int main()
+{
     int i;
     HTS221 hts221;
     pc.baud(115200);
@@ -481,40 +492,33 @@
     // Set LED BLUE for partial init
     SetLedColor(0x4);
 
+    // Create the Pubnub context and message vector
+    pubnub_ctx pb("demo", "demo");
+    std::vector<std::string> messages;
+    
     // Send and receive data perpetually
     while(1) {
         static unsigned ledOnce = 0;
-        if  (bTimerExpiredFlag)
-        {
+        if  (bTimerExpiredFlag) {
             bTimerExpiredFlag = false;
             sprintf(SENSOR_DATA.Temperature, "%0.2f", CTOF(hts221.readTemperature()));
             sprintf(SENSOR_DATA.Humidity, "%02d", hts221.readHumidity());
             read_sensors(); //read available external sensors from a PMOD and the on-board motion sensor
-            char modem_string[512];
-            GenerateModemString(&modem_string[0]);
-            printf(BLU "Sending to modem : %s" DEF "\n", modem_string); 
-            sockwrite_mdm(modem_string);
-            sockread_mdm(&MySocketData, 1024, 20);
             
-            // If any non-zero response from server, make it GREEN one-time
-            //  then the actual FLOW responses will set the color.
-            if ((!ledOnce) && (MySocketData.length() > 0))
-            {
+            char json_string[512];
+            GeneratePubnubJSON(json_string, sizeof json_string);
+            print_pubnub_result(pb.publish("hello_world", json_string));
+            
+            messages.clear();
+            print_pubnub_result(pb.subscribe("hello_world", messages));
+            if (!ledOnce && !messages.empty()) {
                 ledOnce = 1;
                 SetLedColor(0x2);
             }
-            
-            printf(BLU "Read back : %s" DEF "\n", &MySocketData[0]);
-            char myJsonResponse[512];
-            if (extract_JSON(&MySocketData[0], &myJsonResponse[0]))
-            {
-                printf(GRN "JSON : %s" DEF "\n", &myJsonResponse[0]);
-                parse_JSON(&myJsonResponse[0]);
-            }
-            else
-            {
-                printf(RED "JSON : %s" DEF "\n", &myJsonResponse[0]); //most likely an incomplete JSON string
-                parse_JSON(&myJsonResponse[0]); //This is risky, as the string may be corrupted
+            for (std::vector<std::string>::iterator it = messages.begin(); it != messages.end(); ++it) {
+                char const *s = it->c_str();
+                printf(BLU "Pubnub message: %s" DEF "\n", s);
+                parse_JSON(s);
             }
         } //bTimerExpiredFlag
     } //forever loop