Guest User

Sending Temperature Data To Cloud Tutorial with ThingsAI.IO

a guest
Dec 31st, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <SoftwareSerial.h>
  2. SoftwareSerial mySerial(12, 13); // RX, TX
  3.  
  4. #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
  5. #include <DNSServer.h>
  6. #include <ESP8266WebServer.h>
  7. #include "WiFiManager.h"          //https://github.com/tzapu/WiFiManager
  8. #include <WiFiClientSecure.h>
  9.  
  10. int count=0,i,m,j,k;
  11. int t,t1,t2,t3;
  12. int outputpin= A0;//ds18b20
  13.  
  14. //////////////////////////////////////// ALL DECLARATIONS for CLOUD //////////////////////////////
  15. const char* host = "api.thingsai.io";                                 // OR host = devapi2.thethingscloud.com
  16. const char* post_url = "/devices/deviceData";       // OR /api/v2/thingscloud2/_table/data_ac
  17. const char* time_server = "baas.thethingscloud.com";             //this is to convert timestamp
  18. const int httpPort = 80;
  19. const int httpsPort = 443;
  20. const char*  server = "api.thingsai.io";  // Server URL
  21.  
  22. char timestamp[10];
  23.  
  24. WiFiClient client;
  25.  
  26.  
  27. /////////////////////////////////////////////////////////////////////////////////////////////////////////
  28. void configModeCallback (WiFiManager *myWiFiManager)
  29. {
  30.   Serial.println("Entered config mode");             //*-*-*-*-*-*-*-*-*-*-*-*-*-*if control enters this function then net is not connected
  31.   Serial.println(WiFi.softAPIP());                  // "WiFi.softAPIP() is for AP" , "WiFi.localIP() is for STA",
  32.                                                                
  33.   Serial.println(myWiFiManager->getConfigPortalSSID());             //if you used auto generated SSID, print it
  34. }
  35. /////////////////////////////////////// TIMESTAMP CALCULATION function///////////////////////////////////////
  36. int GiveMeTimestamp()
  37. {
  38.   unsigned long timeout = millis();
  39.  
  40.   while (client.available() == 0)
  41.   {
  42.     if (millis() - timeout > 50000)
  43.     {
  44.       client.stop();
  45.       return 0;
  46.     }
  47.   }
  48.  
  49. while (client.available())
  50.       {
  51.         String line = client.readStringUntil('\r');                    //indexOf() is a funtion to search for smthng , it returns -1 if not found
  52.         int pos = line.indexOf("\"timestamp\"");                       //search for "\"timestamp\"" from beginning of response got and copy all data after that , it'll be your timestamp
  53.         if (pos >= 0)                                                    
  54.         {
  55.           int j = 0;
  56.           for(j=0;j<10;j++)
  57.           {
  58.             timestamp[j] = line[pos + 12 + j];
  59.           }
  60.         }
  61.       }
  62. }  
  63. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  64.  
  65. void setup()
  66. {
  67.   Serial.begin(115200);     //(19200,SERIAL_8E1) - data size = 8 bits , parity = Even , stop bit =  1bit
  68.   mySerial.begin(115200);
  69.   WiFiManager wifiManager;
  70.  
  71.   wifiManager.setAPCallback(configModeCallback);
  72.                                                                                                    
  73.   if(!wifiManager.autoConnect("abcd","*****"))                   //wifiManager.autoConnect("AP-NAME", "AP-PASSWORD"); (OR) wifiManager.autoConnect("AP-NAME"); only ID no password (OR) wifiManager.autoConnect(); this will generate a ID by itself
  74.   {
  75.     Serial.println("failed to connect and hit timeout");     //control comes here after long time of creating Access point "NodeMCU" by NodeMCU and still it has not connected
  76.     //reset and try again, or maybe put it to deep sleep
  77.     ESP.reset();
  78.     delay(1000);
  79.   }
  80.  
  81.   //if you come here you have connected to the WiFi
  82.   Serial.println("connected...yeey :");
  83.  
  84. }
  85.  
  86. void loop()
  87. {
  88.   int analogValue = analogRead(outputpin);
  89. {
  90.  
  91.  
  92.  
  93. /////////////////////////////////////// SEND THE QUERY AND RECEIVE THE RESPONSE///////////////////////  
  94.  t1=(analogValue/1024.0) * 3300;
  95.         Serial.print("temp: ");
  96.         Serial.println(t1);
  97.  
  98.         t2=(t1/10);
  99.         Serial.print("celc: ");
  100.         Serial.println(t2);
  101.  
  102.         t3=((t2 * 9)/5 + 32);
  103.         Serial.print("fhrn: ");
  104.         Serial.println(t3);        //break;
  105.  
  106.          
  107.  
  108.   Serial.print("connecting to ");
  109.   Serial.println(host);                          //defined upside :- host = devapi2.thethingscloud.com or 139.59.26.117
  110.  
  111. ///////////////////////////////////// TIMESTAMP CODE SNIPPET /////////////////////////
  112. Serial.println("inside get timestamp\n");
  113.   if (!client.connect(time_server, httpPort))
  114.   {
  115.     return;                                                        //*-*-*-*-*-*-*-*-*-*
  116.   }
  117.  
  118.   client.println("GET /api/timestamp HTTP/1.1");                            //Whats this part doing, i didnt get
  119.   client.println("Host: baas.thethingscloud.com");
  120.   client.println("Cache-Control: no-cache");
  121.   client.println("Postman-Token: ea3c18c6-09ba-d049-ccf3-369a22a284b8");
  122.   client.println();
  123.  
  124. GiveMeTimestamp();                        //it'll call the function which will get the timestamp response from the server
  125. Serial.println("timestamp receieved");
  126. Serial.println(timestamp);
  127. ///////////////////////////////////////////////////////////////////////////////
  128.  
  129.   Serial.println("inside ThingsCloudPost");
  130.  
  131.  
  132. String PostValue = "{\"device_id\":  20181226, \"slave_id\": 2";
  133.          PostValue = PostValue + ",\"dts\":" +timestamp;
  134.    PostValue = PostValue +",\"data\":{\"celc\":" + t2 +",\"fahr\":" + t3 +"}"+"}";
  135.  
  136.  
  137.   Serial.println(PostValue);
  138.  
  139. /* create an instance of WiFiClientSecure */
  140.     WiFiClientSecure client;
  141.    
  142.     Serial.println("Connect to server via port 443");
  143.     if (!client.connect(server, 443)){
  144.         Serial.println("Connection failed!");
  145.     } else {
  146.         Serial.println("Connected to server!");
  147.         /* create HTTP request */
  148.  
  149.         client.println("POST /devices/deviceData HTTP/1.1");
  150.         client.println("Host: api.thingsai.io");
  151.         //client.println("Connection: close");
  152.         client.println("Content-Type: application/json");
  153.         client.println("cache-control: no-cache");
  154.         client.println("Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.IjVhMzBkZDFkN2QwYjNhNGQzODkwYzQ4OSI.kaY6OMj5cYlWNqC2PNTkXs9PKy6_m9tdW5AG7ajfVlY");
  155.         client.print("Content-Length: ");
  156.         client.println(PostValue.length());
  157.         client.println();
  158.         client.println(PostValue);
  159. //////////////////////////////////POSTING the data on to the cloud is done and now get the response form cloud server//////////////////
  160.  Serial.print("Waiting for response ");
  161.         while (!client.available()){
  162.             delay(50); //
  163.             Serial.print(".");
  164.         }  
  165.         /* if data is available then receive and print to Terminal */
  166.         while (client.available()) {
  167.             char c = client.read();
  168.             Serial.write(c);
  169.         }
  170.  
  171.         /* if the server disconnected, stop the client */
  172.         if (!client.connected()) {
  173.             Serial.println();
  174.             Serial.println("Server disconnected");
  175.             client.stop();
  176.         }
  177.     }
  178. Serial.println("//////////////////////    THE END     /////////////////////");
  179. delay(3000);
  180. }
  181. }
Add Comment
Please, Sign In to add comment