V.06 11/3

Dependencies:   FT6206 SDFileSystem SPI_TFT_ILI9341 TFT_fonts

Fork of ATT_AWS_IoT_demo by attiot

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*
00002  *  AT&T IoT Starter Kit example using Amazon Web Service 
00003  */
00004 #include "mbed.h"
00005 
00006 //TFT
00007 #include "SPI_TFT_ILI9341.h"
00008 #include "FT6206.h"
00009 #include "Arial12x12.h"
00010 #include "Arial28x28.h"
00011 #include "BookAntiqua19x19-14.h"
00012 
00013 #include "logo.h"
00014 
00015 // SD File System
00016 #include "SDFileSystem.h"
00017 
00018 // Serial extension
00019 #include "MODSERIAL.h"
00020 
00021 // Network includes
00022 #include "WNCInterface.h"
00023 #include "network_interface.h"
00024 
00025 // AWS includes
00026 #include "aws_iot_log.h"
00027 #include "aws_iot_version.h"
00028 #include "aws_iot_shadow_interface.h"
00029 #include "aws_iot_shadow_json_data.h"
00030 #include "aws_iot_config.h"
00031 #include "aws_iot_mqtt_interface.h"
00032 
00033 #include "mbedtls/net.h"
00034 #include "mbedtls/ssl.h"
00035 #include "mbedtls/entropy.h"
00036 #include "mbedtls/ctr_drbg.h"
00037 #include "mbedtls/certs.h"
00038 #include "mbedtls/x509.h"
00039 #include "mbedtls/error.h"
00040 #include "mbedtls/debug.h"
00041 #include "mbedtls/timing.h"
00042 #include "mbedtls/net_sockets.h"
00043 #include "pem.h"
00044 
00045 
00046 // Sensors
00047 #include "HTS221.h"
00048 
00049 #if DEBUG_LEVEL > 0
00050 #include "mbedtls/debug.h"
00051 #endif
00052 
00053 
00054 
00055 //=====================================================================================================================
00056 //
00057 // Defines
00058 //
00059 //=====================================================================================================================
00060 // LED Colors
00061 #define COLOR_OFF    0x00
00062 #define COLOR_RED    0x01
00063 #define COLOR_GREEN  0x02
00064 #define COLOR_BLUE   0x04
00065 #define COLOR_WHITE  0x07
00066 #define NUM_COLORS   5
00067 
00068 // AWS defines
00069 #define PATH_MAX    1024
00070 #define MAX_LENGTH_OF_UPDATE_JSON_BUFFER 200 // NOTE: Be wary of this if your JSON doc grows
00071 #define SHADOW_SYNC_INTERVAL 6.0             // How often we sync with AWS Shadow (in seconds)
00072 
00073 // Comment out the following line if color is not supported on the terminal
00074 //#define USE_COLOR
00075 #ifdef USE_COLOR
00076  #define BLK "\033[30m"
00077  #define RED "\033[31m"
00078  #define GRN "\033[32m"
00079  #define YEL "\033[33m"
00080  #define BLU "\033[34m"
00081  #define MAG "\033[35m"
00082  #define CYN "\033[36m"
00083  #define WHT "\033[37m"
00084  #define DEF "\033[39m"
00085 #else
00086  #define BLK
00087  #define RED
00088  #define GRN
00089  #define YEL
00090  #define BLU
00091  #define MAG
00092  #define CYN
00093  #define WHT
00094  #define DEF
00095 #endif
00096 
00097 // Sensor defines
00098 #define CTOF(x)  ((x)*1.8+32) // Temperature
00099 
00100 //TFT
00101 #define PIN_SCLK        PTD5
00102 #define PIN_MISO        PTD7
00103 #define PIN_MOSI        PTD6
00104 #define PIN_CS_TFT      PTD4  // chip select pin
00105 #define PIN_DC_TFT      PTB20  // data/command select pin.
00106 #define PIN_RESET_TFT   PTB20  //we don't need reset so just use DC instead. Could modify library
00107 
00108 #define PORTRAIT        0
00109 #define LANDSCAPE       1
00110 #define LANDSCAPE_R     3
00111 
00112 //#if 0
00113 /*
00114 #define PIN_SCL_FT6206  PTE24
00115 #define PIN_SDA_FT6206  PTE25
00116 //#define PIN_INT_FT6206  PTC6
00117 #define PIN_INT_FT6206  PTC3
00118 */
00119 //#else
00120 
00121 #define PIN_SCL_FT6206  D15
00122 #define PIN_SDA_FT6206  D14
00123 #define PIN_INT_FT6206  PTC3
00124 
00125 //#endif
00126 
00127 
00128 
00129 SPI_TFT_ILI9341 TFT(PIN_MOSI, PIN_MISO, PIN_SCLK, PIN_CS_TFT, PIN_RESET_TFT, PIN_DC_TFT, "TFT"); // mosi, miso, sclk, cs, reset, dc 
00130 FT6206 ft6206(PIN_SDA_FT6206, PIN_SCL_FT6206, PIN_INT_FT6206); // sda, scl, int
00131 
00132 //=====================================================================================================================
00133 //
00134 // Globals
00135 //
00136 //=====================================================================================================================
00137 // Controls LED color
00138 unsigned char ledColor = COLOR_OFF;
00139 
00140 // Color cycle array (used with SW3 button presses)
00141 unsigned char colorCycle[NUM_COLORS] = {COLOR_OFF, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_WHITE};
00142 
00143 // Button interrupts
00144 bool buttonOverride = false;
00145 InterruptIn Interrupt(SW3);
00146 
00147 // These defines are pulled from aws_iot_config.h
00148 char HostAddress[255] = AWS_IOT_MQTT_HOST1;
00149 char MqttClientID[32] = AWS_IOT_MQTT_CLIENT_ID;
00150 char ThingName[32] = AWS_IOT_MY_THING_NAME;
00151 char PortString[5] = "8883";
00152 uint32_t port = AWS_IOT_MQTT_PORT;
00153 char iccidName[21] = "12345678901234567890";
00154 
00155 // Sensor data
00156 float temperature = 0.0;
00157 int   humidity    = 0;
00158 unsigned int count = 1;
00159 
00160 char iccid[] = "89011702278124165220";
00161 
00162 //mqqt host name
00163 char *aws_iot_mqtt_host;
00164 
00165 //certificate
00166 static mbedtls_x509_crt clicert;
00167 
00168 // Temp/humidity object
00169 HTS221 hts221; 
00170 
00171 
00172 
00173 //=====================================================================================================================
00174 //
00175 // Devices
00176 //
00177 //=====================================================================================================================
00178 // GPIOs for RGB LED
00179 DigitalOut led_green(LED_GREEN);
00180 DigitalOut led_red(LED_RED);
00181 DigitalOut led_blue(LED_BLUE);
00182 
00183 // USB Serial port (to PC)
00184 MODSERIAL pc(USBTX,USBRX,256,256);
00185 
00186 // SD card access (MOSI, MISO, SCK, CS)
00187 SDFileSystem sd(PTE3, PTE1, PTE2, PTE4, "sd");
00188 
00189 // I2C bus (SDA, SCL)
00190 I2C i2c(PTC11, PTC10);
00191 
00192 extern unsigned char cSubject[100];
00193 
00194 int16_t dbm;
00195 unsigned char cUpdateStatus = 0x00;
00196 
00197 //=====================================================================================================================
00198 //
00199 // Functions
00200 //
00201 //=====================================================================================================================
00202 //*********************************************************************************************************************
00203 //* Prints the given format to the PC serial port.  Exposed to all files via aws_iot_log.h
00204 //*********************************************************************************************************************
00205 void pc_print(const char * format, ...)
00206 {
00207     va_list vl;
00208     va_start(vl, format);
00209     pc.vprintf(format, vl);
00210     va_end(vl);
00211 }
00212 
00213 //*********************************************************************************************************************
00214 //* Set the RGB LED's Color
00215 //* LED Color 0=Off to 7=White.  3 bits represent BGR (bit0=Red, bit1=Green, bit2=Blue) 
00216 //*********************************************************************************************************************
00217 void SetLedColor(unsigned char ucColor)
00218 {    
00219     //Note that when an LED is on, you write a 0 to it:
00220     led_red = !(ucColor & 0x1); //bit 0
00221     led_green = !(ucColor & 0x2); //bit 1
00222     led_blue = !(ucColor & 0x4); //bit 2
00223 }
00224 
00225 //*********************************************************************************************************************
00226 //* SW3 Button handler.  Finds the current LED color and sets the button to the next color in colorCycle[]
00227 //*********************************************************************************************************************
00228 void sw3ButtonHandler()
00229 {
00230     int i;
00231     for(i=0; i < NUM_COLORS; i++) {
00232         if (ledColor == colorCycle[i])
00233             break;
00234     }
00235     
00236     // (circular-queue)
00237     if (++i == NUM_COLORS)
00238         i = 0;
00239         
00240     ledColor = colorCycle[i];
00241     SetLedColor(ledColor);
00242     buttonOverride = true;
00243 }
00244 
00245 //*********************************************************************************************************************
00246 //* Print LED and sensor data
00247 //*********************************************************************************************************************
00248 void printData()
00249 {
00250     INFO("Temperature is: %0.2f F", temperature);
00251     INFO("Humidity    is: %02d", humidity);    
00252     
00253     switch (ledColor) {
00254          case COLOR_OFF:
00255              INFO("LED: Off");
00256              
00257              break;
00258          case COLOR_RED:
00259              INFO("LED: Red");
00260              
00261              break;
00262          case COLOR_GREEN:
00263              INFO("LED: Green");
00264              break;
00265          case COLOR_BLUE:
00266              INFO("LED: Blue");
00267              break;
00268          case COLOR_WHITE:
00269              INFO("LED: White");
00270              break;
00271     }
00272     
00273 }
00274 
00275 /*
00276 void printDatatoTFT()
00277 {
00278     //TFT.cls();
00279     TFT.locate(0,10);
00280     TFT.printf("ATT LTE: %d dBm      AWS: Connected\n\n", dbm);
00281     //TFT.line (0,21, 320,21, White);
00282     TFT.printf("Certificate Name: %s\n\n", cSubject);
00283     //TFT.printf("Sending Device Data...\n\n");
00284     TFT.printf("ICCID:      %s\n", iccidName);
00285     TFT.printf("Temperature: %0.2f F    \n", temperature);
00286     TFT.printf("Humidity:    %02d %%\n", humidity);
00287     TFT.printf("LED:       ");
00288     
00289     switch (ledColor) {
00290          case COLOR_OFF:
00291              TFT.foreground(White);
00292              TFT.printf("OFF     \n");
00293              TFT.fillcircle (240,160, 25, Black);
00294              TFT.circle (240,160, 25, White);
00295              break;
00296          case COLOR_RED:
00297              TFT.foreground(Red);
00298              TFT.printf("RED     \n");
00299              TFT.foreground(White);
00300              TFT.fillcircle (240,160, 25, Red);
00301              break;
00302          case COLOR_GREEN:
00303              TFT.foreground(Green);
00304              TFT.printf("GREEN   \n");
00305              TFT.foreground(White);
00306              TFT.fillcircle (240,160, 25, Green);
00307              break;
00308          case COLOR_BLUE:
00309              TFT.foreground(Blue);
00310              TFT.printf("BLUE   \n");
00311              TFT.foreground(White);
00312              TFT.fillcircle (240,160, 25, Blue);
00313              break;
00314          case COLOR_WHITE:
00315              TFT.foreground(White);
00316              TFT.printf("WHITE   \n");
00317              TFT.fillcircle (240,160, 25, White);
00318              break;
00319     }
00320     TFT.printf("\nUpdate Count: %d\n", count++);
00321 }
00322 */
00323 
00324 void printDatatoTFT()
00325 {
00326     //TFT.cls();
00327     TFT.locate(0,10);
00328     TFT.printf("ATT LTE: %d dBm AWS: %d\n\n", dbm, count++);
00329     //TFT.line (0,21, 320,21, White);
00330     TFT.printf("CN: %s\n", cSubject);
00331     //TFT.printf("Sending Device Data...\n\n");
00332     TFT.printf("ICCID: %s\n", iccidName);
00333     TFT.printf("TEMPERATURE: %0.2f F    \n", temperature);
00334     TFT.printf("HUMIDITY: %02d %%\n", humidity);
00335     TFT.printf("LED: ");
00336     
00337     switch (ledColor) {
00338          case COLOR_OFF:
00339              TFT.foreground(White);
00340              TFT.printf("OFF     \n");
00341              TFT.fillcircle (240,160, 25, Black);
00342              TFT.circle (240,160, 25, White);
00343              break;
00344          case COLOR_RED:
00345              TFT.foreground(Red);
00346              TFT.printf("RED     \n");
00347              TFT.foreground(White);
00348              TFT.fillcircle (240,160, 25, Red);
00349              break;
00350          case COLOR_GREEN:
00351              TFT.foreground(Green);
00352              TFT.printf("GREEN   \n");
00353              TFT.foreground(White);
00354              TFT.fillcircle (240,160, 25, Green);
00355              break;
00356          case COLOR_BLUE:
00357              TFT.foreground(Blue);
00358              TFT.printf("BLUE   \n");
00359              TFT.foreground(White);
00360              TFT.fillcircle (240,160, 25, Blue);
00361              break;
00362          case COLOR_WHITE:
00363              TFT.foreground(White);
00364              TFT.printf("WHITE   \n");
00365              TFT.fillcircle (240,160, 25, White);
00366              break;
00367     }
00368     //TFT.printf("\nUpdate Count: %d\n", count++);
00369 }
00370 
00371 void ShowINFO(const char *sInfo)
00372 {
00373     INFO(sInfo);
00374     TFT.printf(sInfo);
00375     TFT.printf("\n");
00376 }
00377    
00378 
00379 //=====================================================================================================================
00380 //
00381 // AWS Shadow Callbacks
00382 //
00383 //=====================================================================================================================
00384 //*********************************************************************************************************************
00385 //* This is the callback function that fires when an update is sent.  It will print the update response status.
00386 //*********************************************************************************************************************
00387 void ShadowUpdateStatusCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status,
00388         const char *pReceivedJsonDocument, void *pContextData) {
00389 
00390     INFO("Shadow Update Status Callback");
00391     TFT.printf("\n");
00392     if (status == SHADOW_ACK_TIMEOUT) {
00393         INFO("Update Timeout");
00394     } else if (status == SHADOW_ACK_REJECTED) {
00395         INFO("Update Rejected");
00396     } else if (status == SHADOW_ACK_ACCEPTED) {
00397         INFO("Update Accepted"); // Good
00398     }
00399     
00400 }
00401 
00402 //*********************************************************************************************************************
00403 //* This is the callback function that fires when AWS has sends out a shadow update. 
00404 //*********************************************************************************************************************
00405 void ledControl_Callback(const char *pJsonString, uint32_t JsonStringDataLen, jsonStruct_t *pContext) {
00406     
00407     INFO("LED Callback Detected.");
00408     
00409     if (pContext != NULL) {
00410         switch (*(unsigned char *)(pContext->pData)){   
00411             case COLOR_OFF:
00412                 INFO("LED -> OFF (%d)", *(unsigned char *)(pContext->pData));
00413                 break;
00414             case COLOR_RED:
00415                 INFO("LED -> RED (%d)", *(unsigned char *)(pContext->pData));
00416                 break;
00417             case COLOR_GREEN:
00418                 INFO("LED -> GREEN (%d)", *(unsigned char *)(pContext->pData));
00419                 break;
00420             case COLOR_BLUE:
00421                 INFO("LED -> BLUE (%d)", *(unsigned char *)(pContext->pData));
00422                 break;
00423             case COLOR_WHITE:
00424                 INFO("LED -> WHITE (%d)", *(unsigned char *)(pContext->pData));
00425                 break;    
00426         }
00427     }
00428     else {
00429         INFO("pContext was detected as NULL");
00430     }
00431 }
00432  
00433 //*********************************************************************************************************************
00434 //* Subscribe callback (used with alternate demo)
00435 //*********************************************************************************************************************
00436 int MQTTcallbackHandler(MQTTCallbackParams params) {
00437 
00438     INFO("Subscribe callback");
00439     INFO("%.*s\t%.*s",
00440             (int)params.TopicNameLen, params.pTopicName,
00441             (int)params.MessageParams.PayloadLen, (char*)params.MessageParams.pPayload);
00442 
00443     return 0;
00444 }
00445 
00446 //*********************************************************************************************************************
00447 //* Disconnect handling (used with alternate demo)
00448 //*********************************************************************************************************************
00449 void disconnectCallbackHandler(void) {
00450     WARN("MQTT Disconnect");
00451     IoT_Error_t rc = NONE_ERROR;
00452     if(aws_iot_is_autoreconnect_enabled()){
00453         INFO("Auto Reconnect is enabled, Reconnecting attempt will start now");
00454     }else{
00455         WARN("Auto Reconnect not enabled. Starting manual reconnect...");
00456         rc = aws_iot_mqtt_attempt_reconnect();
00457         if(RECONNECT_SUCCESSFUL == rc){
00458             WARN("Manual Reconnect Successful");
00459         }else{
00460             WARN("Manual Reconnect Failed - %d", rc);
00461         }
00462     }
00463 }
00464 
00465 //=====================================================================================================================
00466 //
00467 // Out-of-Box Demo: This function is used as part of the binary that comes with the Starter Kit.  Instead of using an
00468 //                  AWS device shadow, it publishes to an AWS Rule. The Rule is setup to store data to a DynamoDB, and
00469 //                  the demo S3 website pulls that data from the DynamoDB and displays it.
00470 //
00471 //=====================================================================================================================
00472 int outOfBoxDemo() {
00473     INFO("Running Out-of-Box Function (alternate demo).");
00474     
00475     IoT_Error_t rc = NONE_ERROR;
00476     int32_t i = 0;
00477     int publishCount = 0;
00478     bool infinitePublishFlag = true;
00479     char cPayload[100];
00480     char cTopic[100];
00481     const string colorStrings[] = {"Off", "Red", "Green", "", "Blue", "", "", "White"};
00482     float updateInterval = 1.0; // seconds
00483 
00484     MQTTConnectParams connectParams = MQTTConnectParamsDefault;
00485     connectParams.KeepAliveInterval_sec = 10;
00486     connectParams.isCleansession = true;
00487     connectParams.MQTTVersion = MQTT_3_1_1;
00488     connectParams.pClientID = iccidName;  // Using ICCID for unique Client ID
00489     connectParams.pHostURL = HostAddress;
00490     connectParams.port = port;
00491     connectParams.isWillMsgPresent = false;
00492     connectParams.pRootCALocation = AWS_IOT_ROOT_CA_FILENAME;
00493     connectParams.pDeviceCertLocation = AWS_IOT_CERTIFICATE_FILENAME;
00494     connectParams.pDevicePrivateKeyLocation = AWS_IOT_PRIVATE_KEY_FILENAME;
00495     connectParams.mqttCommandTimeout_ms = 10000;
00496     connectParams.tlsHandshakeTimeout_ms = 10000;
00497     connectParams.isSSLHostnameVerify = true; // ensure this is set to true for production
00498     connectParams.disconnectHandler = disconnectCallbackHandler;
00499 
00500     INFO("Connecting...");
00501     rc = aws_iot_mqtt_connect(&connectParams);
00502     if (NONE_ERROR != rc) {
00503         ERROR("Error(%d) connecting to %s:%d", rc, connectParams.pHostURL, connectParams.port);
00504     }
00505     
00506     /*
00507      * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
00508      *  #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
00509      *  #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
00510      */
00511     INFO("Set Auto Reconnect...");
00512     rc = aws_iot_mqtt_autoreconnect_set_status(true);
00513     if (NONE_ERROR != rc) {
00514         ERROR("Unable to set Auto Reconnect to true - %d", rc);
00515         return rc;
00516     }
00517 
00518     // Comment this in if you want to subscribe
00519     /*MQTTSubscribeParams subParams = MQTTSubscribeParamsDefault;
00520     subParams.mHandler = MQTTcallbackHandler;
00521     subParams.pTopic = "sdkTest/sub";
00522     subParams.qos = QOS_0;
00523 
00524     if (NONE_ERROR == rc) {
00525         INFO("Subscribing...");
00526         rc = aws_iot_mqtt_subscribe(&subParams);
00527         if (NONE_ERROR != rc) {
00528             ERROR("Error subscribing");
00529         }
00530     }*/
00531 
00532     // Initializ the payload
00533     MQTTMessageParams Msg = MQTTMessageParamsDefault;
00534     Msg.qos = QOS_0;
00535     Msg.pPayload = (void *) cPayload;
00536 
00537     MQTTPublishParams Params = MQTTPublishParamsDefault;
00538     
00539     // Sets up the topic to publish to
00540     sprintf(cTopic, AWS_IOT_MY_TOPIC, iccidName);
00541     Params.pTopic = cTopic;
00542 
00543     if (publishCount != 0) {
00544         infinitePublishFlag = false;
00545     }
00546       
00547     INFO("READY TO PUBLISH! Press SW3 button to publish current data.");
00548     while ((NETWORK_ATTEMPTING_RECONNECT == rc || RECONNECT_SUCCESSFUL == rc || NONE_ERROR == rc)
00549             && (publishCount > 0 || infinitePublishFlag)) {
00550 
00551         // Max time the yield function will wait for read messages
00552         rc = aws_iot_mqtt_yield(100);
00553         if(NETWORK_ATTEMPTING_RECONNECT == rc){
00554             INFO("--> sleep (attempting to reconnect)");
00555             wait(1);
00556             // If the client is attempting to reconnect we will skip the rest of the loop.
00557             continue;
00558         }
00559         
00560         // Whenever the software button (SW3) is pressed the LED will changes color and this will
00561         // trigger a publish to the AWS topic specified.
00562         if (buttonOverride) {
00563             buttonOverride = false;
00564             
00565             // Get temp/humidity values
00566             temperature = CTOF(hts221.readTemperature());
00567             humidity = hts221.readHumidity();
00568     
00569             // Loading data into JSON format
00570             sprintf(cPayload, "{\"color\":\"%s\",\"temperature\":%f,\"humidity\":%d}", colorStrings[ledColor], temperature, humidity);
00571             Msg.PayloadLen = strlen(cPayload) + 1;
00572             Params.MessageParams = Msg;
00573             
00574             // Publish
00575             rc = aws_iot_mqtt_publish(&Params);
00576             if (publishCount > 0) {
00577                 publishCount--;
00578             }
00579                       
00580             printData();
00581             INFO("--> Update sent. Sleep for %f seconds", updateInterval);
00582             wait(updateInterval-.02);
00583         }
00584         else {
00585             wait(.3); // 300 ms
00586         }
00587     }
00588 
00589     if (NONE_ERROR != rc) {
00590         ERROR("An error occurred in the loop.\n");
00591     } else {
00592         INFO("Publish done\n");
00593     }
00594 
00595     return rc;
00596 }
00597 
00598 void InitTFT()
00599 {
00600     //Configure the display driver
00601     TFT.claim(stdout);
00602     TFT.background(Black);
00603     TFT.foreground(White);
00604     TFT.set_orientation(LANDSCAPE_R);
00605     TFT.cls();
00606     TFT.set_font((unsigned char*) Arial12x12);
00607     //TFT.set_font((unsigned char*) Courier10x13-12B);
00608     TFT.locate(0,0);
00609 }
00610 
00611 void TFTStuff()
00612 {
00613     INFO("DBG> main\r\n");
00614     
00615     //FT6206 ft6206(PIN_SDA_FT6206, PIN_SCL_FT6206, PIN_INT_FT6206); // sda, scl, int
00616 
00617     //Configure the display driver
00618     TFT.claim(stdout);
00619     TFT.background(Black);
00620     TFT.foreground(White);
00621     
00622     //TFT.background(White);
00623     //TFT.foreground(Black);
00624 
00625     
00626     TFT.set_orientation(LANDSCAPE_R);
00627     TFT.cls();
00628 
00629     //Print a welcome message
00630     TFT.set_font((unsigned char*) Arial12x12);
00631     TFT.locate(0,0);
00632     TFT.printf("Hello mbed!\n");
00633     TFT.printf("Touch Screen to Continue!\n");
00634     INFO("Hello mbed!\r\n");
00635     INFO("Touch Screen to Continue!!\r\n");
00636     
00637     int X1, Y1, X2, Y2;
00638     TS_Point p;
00639     
00640     while(1) {
00641         
00642         if(ft6206.touched())
00643         {
00644             INFO("Touched\r\n");
00645             p = ft6206.getPoint();
00646             
00647             
00648             X1 = TFT.width()-p.x;
00649             Y1 = TFT.height()-p.y;
00650             pc.printf("Touched at x=%3d y=%3d\n", p.x, p.y);
00651             pc.printf("Touched actual at x=%3d y=%3d\n", X1, Y1);
00652             
00653             //ft6206.clearPoint();
00654             //return;
00655         }
00656 /*
00657         if (ft6206.getTouchPoint(p)) {
00658             X1 = X2;
00659             Y1 = Y2;
00660             X2 = TFT.width()-p.x;
00661             Y2 = TFT.height()-p.y;
00662             TFT.locate(0,12);
00663             INFO("Touch %3d %3d\n", p.x, p.y);
00664             return;
00665             if ((X1 > 0) && (Y1 > 0) && (X2 > 0) && (Y2 > 0)) {
00666                 TFT.line(X1, Y1, X2, Y2, RGB(255,128,255));
00667             }
00668         }
00669 */
00670     }
00671     
00672 }
00673 /*
00674 //=====================================================================================================================
00675 // setupShield
00676 // setup the Adrafruit 1947
00677 //=====================================================================================================================
00678 void setupShield(bool touch) {
00679     //Configure the display driver
00680     TFT.claim(stdout);
00681     TFT.background(Black);
00682     TFT.foreground(White);
00683     TFT.set_orientation(LANDSCAPE);
00684         
00685     TFT.cls();
00686     INFO("TFT.cls()");
00687     
00688     TFT.circle(120, 120, 50, Red);
00689 
00690     //Print a welcome message
00691     TFT.set_font((unsigned char*) Arial12x12);
00692     TFT.locate(120,160);
00693     TFT.printf("Hello G+D!\n");
00694 
00695    if (touch) {
00696        while (0)
00697         if(pc.readable())
00698                 pc.putc(pc.getc());    
00699 
00700        int X1, Y1, X2, Y2 = 0;
00701         X2 = -100;
00702         while(1) {
00703             if (FT6206.touched()) {
00704     //        if (FT6206.dataReceived()) {
00705     //            led1 = !led1;
00706                 // Retrieve a point  
00707                 TS_Point p = FT6206.getPoint();
00708                 X1 = X2;
00709                 Y1 = Y2;
00710                 X2 = p.x;
00711                 Y2 = p.y;
00712     //            printf("Touch %3d %3d\n", p.x, p.y);
00713                 if ((X1 > 0) && (Y1 > 0) && (X2 > 0) && (Y2 > 0)) {
00714                     TFT.line(X1, Y1, X2, Y2, Green);
00715                 }
00716             }
00717     //        TFT.printf("Count: %d\n", count++);
00718             wait(0.05);
00719         }
00720     }
00721 }
00722 */
00723 
00724 int DoAWSThingMenu()
00725 {
00726     
00727     //FT6206 ft6206(PIN_SDA_FT6206, PIN_SCL_FT6206, PIN_INT_FT6206); // sda, scl, int
00728     
00729     TFT.cls();
00730     TFT.locate(0,3);
00731     INFO ("AWS Host Selection\n");
00732     TFT.set_font((unsigned char*) Book_Antiqua19x19);
00733     TFT.printf ("     SELECT AWS HOST\n");
00734     
00735     TFT.set_font((unsigned char*) Arial28x28);
00736     //TFT.circle (160,65, 40, Blue);
00737     TFT.fillcircle (160,75, 40, Blue);
00738     TFT.locate(130,63);
00739     //TFT.foreground(Blue);
00740     TFT.background(Blue);
00741     TFT.foreground(Red);
00742     TFT.printf("ATT");
00743     //TFT.line (0,39, 319, 39, White);
00744     //TFT.circle (160,150, 40, Green);
00745     TFT.fillcircle (160,160, 40, Green);
00746     TFT.locate(137, 148);
00747     //TFT.foreground(Green);
00748     TFT.background(Green);
00749     TFT.foreground(Black);
00750     TFT.printf("GD");
00751     //TFT.line (0,79, 319, 79, White);   
00752     
00753     int X1, Y1, X2, Y2;
00754     TS_Point p;
00755     
00756     
00757     while(1) 
00758     {
00759          if(ft6206.touched())
00760          {
00761             p = ft6206.getPoint();
00762             X1 = TFT.width()-p.x;
00763             Y1 = TFT.height()-p.y;
00764 
00765             //pc.printf("Touched at x=%3d y=%3d\n", p.x, p.y);
00766             //pc.printf("Touched actual at x=%3d y=%3d\n", X1, Y1);
00767 
00768             if ((X1 > 120) && (X1 < 200) && (Y1 > 35) && (Y1 <115))
00769             {
00770                 INFO("ATT selected\r\n");
00771                 return 1;
00772             }
00773             
00774             if ((X1 > 120) && (X1 < 200) && (Y1 > 120) && (Y1 < 200))
00775             {
00776                 INFO ("GD selected\n");
00777                 return 2;
00778             }
00779          
00780             //ft6206.clearPoint();
00781         }
00782         
00783     }
00784     pc.printf ("leaving menu\n"); 
00785     wait (10.0);
00786     //TFT.set_font((unsigned char*) Arial12x12);
00787     TFT.set_font((unsigned char*) Book_Antiqua19x19);
00788     TFT.foreground(White);
00789     return 0;    
00790 }
00791 
00792 //=====================================================================================================================
00793 //
00794 // Main
00795 //
00796 //=====================================================================================================================
00797 int main() 
00798 {
00799     bool bFirstTime = true;
00800     
00801     //Init Screen
00802     InitTFT();
00803     
00804     // Set baud rate for PC Serial
00805     pc.baud(115200);
00806     ShowINFO("AT&T AWS IoT Demo V.06");
00807     
00808     TFT.drawBitmap(43, 10, att, 234, 96);
00809     TFT.drawBitmap(0, 150, gd, 320, 56);  
00810 
00811                
00812     int i;          
00813     IoT_Error_t rc = NONE_ERROR;  
00814     char JsonDocumentBuffer[MAX_LENGTH_OF_UPDATE_JSON_BUFFER];
00815     size_t sizeOfJsonDocumentBuffer = sizeof(JsonDocumentBuffer) / sizeof(JsonDocumentBuffer[0]);
00816 
00817     // JSON struct for LED control
00818     jsonStruct_t ledController;
00819     ledController.cb = ledControl_Callback;
00820     ledController.pData = &ledColor;
00821     ledController.pKey = "ledColor";
00822     ledController.type = SHADOW_JSON_UINT8;
00823 
00824     // JSON struct for temperature\humidity readings
00825     jsonStruct_t temperatureHandler;
00826     temperatureHandler.cb = NULL;
00827     temperatureHandler.pKey = "temperature";
00828     temperatureHandler.pData = &temperature;
00829     temperatureHandler.type = SHADOW_JSON_FLOAT;
00830     
00831     jsonStruct_t humidityHandler;
00832     humidityHandler.cb = NULL;
00833     humidityHandler.pKey = "humidity";
00834     humidityHandler.pData = &humidity;
00835     humidityHandler.type = SHADOW_JSON_INT16;
00836     
00837     jsonStruct_t iccidHandler;
00838     iccidHandler.cb = NULL;
00839     iccidHandler.pKey = "iccid";
00840     iccidHandler.pData = iccidName;
00841     iccidHandler.type = SHADOW_JSON_STRING;
00842     
00843     
00844     INFO("AWS IoT SDK Version(dev) %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
00845     
00846 
00847 #ifdef USING_SD_CARD
00848     // Paths for certs from SD card
00849     INFO("Using SD card files for AWS config.");  
00850     DEBUG("- mqtt config path: %s", AWS_MQTT_CONFIG_FILENAME);
00851     DEBUG("- rootCA path: %s", AWS_IOT_ROOT_CA_FILENAME);
00852     DEBUG("- clientCRT path: %s", AWS_IOT_CERTIFICATE_FILENAME);
00853     DEBUG("- clientKey path: %s", AWS_IOT_PRIVATE_KEY_FILENAME);
00854 #else
00855     //INFO("Using #defines in aws_iot_config.h and certs from certs.cpp for AWS config.");      
00856 #endif
00857     
00858     // Startup signal - blinks through RGBW then turns off
00859     SetLedColor(COLOR_RED);
00860     wait(.5);
00861     SetLedColor(COLOR_GREEN);
00862     wait(.5);
00863     SetLedColor(COLOR_BLUE);
00864     wait(.5);
00865     SetLedColor(COLOR_WHITE);
00866     wait(.5);
00867     SetLedColor(COLOR_OFF);
00868     
00869     //TFTStuff();
00870     
00871     // Initialize sensors
00872     INFO("Init sensors...");
00873     void hts221_init(void);
00874     i = hts221.begin();  
00875     if(!i) {
00876         WARN(RED "HTS221 NOT DETECTED!!\n\r");
00877     }
00878     
00879     //TFTStuff();
00880     wait (2.0);
00881     int iSelection = 0;
00882     string sMQTTHostName;
00883     
00884     iSelection = DoAWSThingMenu();
00885     
00886     TFT.locate(0,0);
00887     //TFT.set_font((unsigned char*) Arial12x12);
00888     TFT.set_font((unsigned char*) Book_Antiqua19x19);
00889     TFT.background(Black);
00890     TFT.foreground(White);
00891     TFT.cls();
00892     switch (iSelection)
00893     {
00894         case 1:
00895             aws_iot_mqtt_host = AWS_IOT_MQTT_HOST1;
00896             sMQTTHostName = "ATT";
00897             TFT.printf ("ATT AWS Host Selected\n");
00898             break;
00899         case 2:
00900             aws_iot_mqtt_host = AWS_IOT_MQTT_HOST2;
00901             sMQTTHostName = "GD";
00902             TFT.printf ("GD AWS Host Selected\n");
00903             break;
00904         default:
00905             ShowINFO ("Unknown MQTT HOST\n");
00906             break;
00907             
00908     }
00909       
00910     // Setup SW3 button to falling edge interrupt
00911     
00912     INFO("Init interrupts...");
00913     Interrupt.fall(&sw3ButtonHandler);
00914     
00915     //TFTStuff();
00916           
00917     // Boot the Avnet Shield before any other operations
00918     INFO("Net Boot...");
00919     TFT.printf ("Connecting to ATT LTE Network....\n");
00920     if (net_modem_boot() != 0)
00921     {
00922         TFT.printf ("Unable to Connect to ATT LTE Network. Please try again by rebooting the device.\n");
00923         return 0;
00924     }
00925     TFT.printf ("Connected to ATT LTE Network.\n");
00926     wait (3.0);
00927     
00928     
00929     if (GetSignalStrength(&dbm) != 0)
00930     {
00931         TFT.printf ("Unable to Signal Strength. Please try again by rebooting the device.\n");
00932         return 0;
00933     }
00934     
00935         
00936     //==========================================================================
00937     // NOTE:  You can comment in the following line for an alternate demo that
00938     // is used as the out-of-box demo binary that comes with the  AT&T IoT 
00939     // Starter Kit.  It loops instead of the rest of Main()
00940     //return outOfBoxDemo();
00941     //==========================================================================
00942 
00943  restart1:   
00944 
00945           
00946     // Intialize MQTT/Cert parameters
00947     ShadowParameters_t sp = ShadowParametersDefault;
00948 #ifdef USING_SD_CARD
00949     rc = (IoT_Error_t)mbedtls_mqtt_config_parse_file(&sp, AWS_MQTT_CONFIG_FILENAME);
00950     if (NONE_ERROR != rc) {
00951         ERROR("Failed to initialize mqtt parameters %d", rc);
00952         return rc;
00953     }   
00954     sp.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME;
00955     sp.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME;
00956     sp.pRootCA = AWS_IOT_ROOT_CA_FILENAME;
00957 #else
00958     sp.pMyThingName = AWS_IOT_MY_THING_NAME;
00959     sp.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID;
00960     //sp.pHost = HostAddress;
00961     INFO ("Host Name:");
00962     INFO (aws_iot_mqtt_host);
00963     sp.pHost = aws_iot_mqtt_host;
00964     INFO (sp.pHost);
00965     sp.port = port;
00966     
00967     sp.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME;
00968     sp.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME;
00969     sp.pRootCA = AWS_IOT_ROOT_CA_FILENAME;
00970 #endif
00971 /*
00972     char cBlockOffset[7];
00973     string sObject;
00974     pc.printf ("Length = %d\n", AWS_IOT_CERTIFICATE_LENGTH );
00975     for (int i = 0; i < AWS_IOT_CERTIFICATE_LENGTH; i++)
00976     {
00977         sprintf (cBlockOffset, "%02X", AWS_IOT_CERTIFICATE[i]);
00978         sObject += string (cBlockOffset);
00979         
00980     }
00981     pc.printf(sObject.c_str());
00982     pc.printf("\n");
00983 */
00984     int ret = 0;
00985     mbedtls_x509_crt_init(&clicert);
00986     ret = mbedtls_x509_crt_parse(&clicert, (const unsigned char *)AWS_IOT_CERTIFICATE, AWS_IOT_CERTIFICATE_LENGTH);
00987     if (ret != 0) {
00988         ERROR(" failed\n  !  mbedtls_x509_crt_parse IOT returned 1 -0x%x,  %d\n\n", -ret, AWS_IOT_CERTIFICATE_LENGTH);
00989         TFT.printf ("Invalid Certificate. Please check the certificate and reboot the device.");
00990         return ret;
00991     }
00992     else
00993     {
00994         for (int i = 0; i < clicert.subject_raw.len; i++)
00995         {
00996             if (clicert.subject_raw.p[i] == 0x0C)
00997             {
00998                 i++;
00999                 unsigned char cLength = clicert.subject_raw.p[i];
01000                 DEBUG ("subject length = %d", cLength);
01001                 i++;
01002                 for (int j = 0; j < (int) cLength; j++)
01003                 {
01004                     cSubject[j] = clicert.subject_raw.p[i];
01005                     i++;
01006                 }
01007                 cSubject[cLength] = 0x00;
01008                 break;
01009             }
01010         }
01011     }   
01012     
01013     TFT.printf("Logging into %s AWS\n", sMQTTHostName); 
01014     TFT.printf("CN: %s\n", cSubject);     
01015     INFO("Initialize the MQTT client...");
01016     MQTTClient_t mqttClient;
01017     aws_iot_mqtt_init(&mqttClient);
01018 
01019     string sAWSError = "\nUnable to Log into AWS. Invalid certificate. Please make sure the certificates in the SIM card are valid and reboot the device.\n";
01020     TFT.printf(".");
01021     INFO("Shadow Init...");
01022     rc = aws_iot_shadow_init(&mqttClient);
01023     if (NONE_ERROR != rc) {
01024         ERROR("Shadow Init Error %d", rc);
01025         TFT.printf(sAWSError.c_str()); 
01026         return rc;
01027     }
01028     
01029     INFO("Shadow Connect...");   
01030     TFT.printf(".");
01031     rc = aws_iot_shadow_connect(&mqttClient, &sp);
01032     if (NONE_ERROR != rc) {
01033         ERROR("Shadow Connection Error %d", rc);
01034         TFT.printf(sAWSError.c_str()); 
01035         return rc;
01036     }
01037 
01038     // Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h
01039     // #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL
01040     // #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL
01041     rc = mqttClient.setAutoReconnectStatus(true);
01042     if (NONE_ERROR != rc) {
01043         ERROR("Unable to set Auto Reconnect to true - %d", rc);
01044         TFT.printf(sAWSError.c_str()); 
01045         return rc;
01046     }
01047     
01048     // Example line of how to delete a shadow (not used in this demo)
01049     //aws_iot_shadow_delete(&mqttClient, AWS_IOT_MY_THING_NAME, ShadowUpdateStatusCallback, NULL, 8, true);
01050 
01051     INFO("Shadow Register Delta...");
01052     TFT.printf(".");
01053     rc = aws_iot_shadow_register_delta(&mqttClient, &ledController);
01054     if (NONE_ERROR != rc) {
01055         ERROR("Shadow Register Delta Error");
01056         TFT.printf(sAWSError.c_str()); 
01057         return rc;
01058     }
01059     
01060     INFO("Will attempt to sync with device shadow every %f seconds.", SHADOW_SYNC_INTERVAL);
01061     // Loop and publish changes from the FRDM board
01062     
01063     while (NETWORK_ATTEMPTING_RECONNECT == rc || RECONNECT_SUCCESSFUL == rc || NONE_ERROR == rc) 
01064     {
01065         
01066         // Looks for incoming socket messages
01067         rc = aws_iot_shadow_yield(&mqttClient, 200);
01068         if (NETWORK_ATTEMPTING_RECONNECT == rc) 
01069         {
01070             // If the client is attempting to reconnect we will skip the rest of the loop.
01071             ShowINFO("Attempting to reconnect...");
01072             wait(1);
01073             bFirstTime = true;
01074             //TFT.cls();
01075             continue;
01076         }
01077         
01078         // Read sensor data
01079         temperature = CTOF(hts221.readTemperature());
01080         humidity = hts221.readHumidity();
01081                                 
01082         INFO("\n=======================================================================================\n");             
01083         // Initialize JSON shadow document          
01084         rc = aws_iot_shadow_init_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer);
01085         if (rc == NONE_ERROR) 
01086         {
01087             
01088             // If there has been a SW3 button press update the 'desired' color
01089             if (buttonOverride) 
01090             {
01091                 rc = aws_iot_shadow_add_desired(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, 1, &ledController);               
01092                 buttonOverride = false;
01093             }
01094                   
01095             // Updates the 'reported' color/temp/humidity
01096             rc = aws_iot_shadow_add_reported(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, 4, &ledController,
01097                                                                                               &temperatureHandler,
01098                                                                                               &humidityHandler, &iccidHandler);
01099                  
01100             if (rc == NONE_ERROR) 
01101             {               
01102                 rc = aws_iot_finalize_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer);   
01103                             
01104                 if (rc == NONE_ERROR) 
01105                 {
01106                     INFO("Update Shadow: %s", JsonDocumentBuffer);
01107                     rc = aws_iot_shadow_update(&mqttClient, sp.pMyThingName, JsonDocumentBuffer,
01108                             ShadowUpdateStatusCallback, NULL, 8, true);
01109                 }
01110             }
01111         }  
01112         
01113         //get signal strength
01114         GetSignalStrength(&dbm);
01115         
01116         //check if certificate is updated
01117         
01118         if (GetUpdateStatus(&cUpdateStatus) != 0)
01119         {
01120             ERROR("Get Update Status Error");
01121         }
01122         else
01123         {
01124             if (cUpdateStatus == 0xFF)
01125             {
01126                 TFT.cls();
01127                 TFT.locate(0,10);
01128                 ShowINFO ("Certifcate Update Detected.");   
01129                 ShowINFO("Disconnecting AWS");
01130                 rc = aws_iot_shadow_disconnect(&mqttClient);
01131                 if (NONE_ERROR != rc) 
01132                 {
01133                     ERROR("Disconnect error %d. Please reboot the device", rc);
01134                     return rc;
01135                 }
01136                 
01137                 if (GetAllObjects() != 0)
01138                 {
01139                     ShowINFO ("Read Certficate Error. Check hardware and Reboot the device..");
01140                     return 0;   
01141                 }
01142                 
01143                 wait(3.0);
01144                 bFirstTime = true;
01145                 goto restart1;
01146             }   
01147         }
01148         
01149         
01150         // Print data
01151         if (bFirstTime == true)
01152         {
01153             TFT.cls();   
01154             bFirstTime = false;
01155         }
01156         printDatatoTFT(); 
01157         printData();
01158         INFO("*****************************************************************************************");
01159          
01160         // Set the LED color    
01161         SetLedColor(ledColor);
01162         wait(SHADOW_SYNC_INTERVAL);
01163         
01164         if (count > 50)
01165         {
01166             INFO ("Max Upload reached. Please reset the device to start again");
01167             TFT.printf ("Max upload reached. Please reset the device to continue.");
01168             return rc;
01169         }
01170             
01171     }
01172 
01173     if (NONE_ERROR != rc) 
01174     {
01175         ERROR("An error occurred in the loop %d", rc);
01176         TFT.printf("Fatal Error. Please reboot the device.\n");
01177     }
01178 
01179     INFO("Disconnecting");
01180     rc = aws_iot_shadow_disconnect(&mqttClient);
01181 
01182     if (NONE_ERROR != rc) {
01183         ERROR("Disconnect error %d", rc);
01184     }
01185 
01186     return rc;   
01187 }