Advertisement
Iv4n

GetTime.cpp (domgiles)

Feb 14th, 2014
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include "digole.h""
  2.  
  3. bool makeRequest = true;
  4. bool waitForResponse = false;
  5. bool getResponse = false;
  6. int lastStepTime = 0;
  7. char response[600];
  8. int responseIndex = 0;
  9.  
  10. DigoleSerialDisp mydisp(SS);
  11.  
  12. void setup() {
  13.   Serial.begin(9600);
  14.     Serial.println("setup");
  15.     pinMode(D0, OUTPUT);
  16.     mydisp.begin();
  17.     mydisp.clearScreen();
  18.     mydisp.setFont(10);
  19.     delay(1000);
  20.     mydisp.println("Starting...");
  21.     String time = http_get("www.timeapi.org", "/utc/now");
  22.     mydisp.println(time);
  23.     mydisp.println("Second Attempt");
  24.     String time2 = http_get("www.timeapi.org", "/utc/now?\\s");
  25.     mydisp.println(time2);
  26.     mydisp.println("Finishing");
  27. }
  28.  
  29. TCPClient client;
  30. char buffer[512];
  31. String http_get(char const* hostname, String path) {
  32.  
  33.     if (client.connect(hostname, 80)) {
  34.         client.print("GET ");
  35.         client.print(path);
  36.         client.print(" HTTP/1.0\n");
  37.         client.print("HOST: ");
  38.         client.println(hostname);
  39.         client.print("\n");
  40.         //  client.print("Connection: close\n\n");
  41.         client.flush();
  42.     } else {
  43.         Serial.println("connection failed");
  44.         mydisp.println("Connection Failed...");
  45.         client.stop();
  46.         return NULL;
  47.     }
  48.  
  49.  
  50.     uint32_t startTime = millis();
  51.     int i = 0;
  52.     while(!client.available() && (millis() - startTime) < 5000);
  53.     while (client.available()) {
  54.         char c = client.read();
  55.         if (c == -1) break;
  56.         Serial.print(c);
  57.         buffer[i] = c;
  58.         i++;
  59.     }
  60.  
  61.     client.stop();
  62.     mydisp.println(buffer);
  63.  
  64.     String response(buffer);
  65.     int bodyPos = response.indexOf("\r\n\r\n");
  66.     if (bodyPos == -1) {
  67.         Serial.println("can not find http reponse body");
  68.         mydisp.println("Can not find http reponse body...");
  69.         return NULL;
  70.     }
  71.     return response.substring(bodyPos + 4);
  72. }
  73.  
  74. void loop() {
  75.      
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement