03_log_data.ino 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include <WiFi.h>
  2. #include <WiFiClientSecure.h>
  3. #define PORT 443
  4. // Connect to example.com as a test method.
  5. void getSomething() {
  6. showProgress(PROGRESS_GREEN);
  7. String content = String("GET / HTTP/1.1\r\n")
  8. + "Host: example.com\r\n"
  9. + "User-Agent: ESP32/FunHouse/tarka-outdoor-weather-station" + "\r\n"
  10. + "Connection: close" + "\r\n";
  11. WiFiClientSecure client;
  12. client.setInsecure();
  13. debug("Connectiong to: example.com");
  14. showProgress(PROGRESS_GREEN);
  15. if(!client.connect("example.com", 443)) {
  16. debug("Connection failed!");
  17. ERR;
  18. }
  19. debug("Connection established. Sending headers & body.");
  20. showProgress(PROGRESS_GREEN);
  21. client.print(content);
  22. // Wait for things to happen
  23. showProgress(PROGRESS_GREEN);
  24. delay(500);
  25. while(client.available()) {
  26. showProgress(PROGRESS_GREEN);
  27. String line = client.readStringUntil('\n');
  28. debug("Read line: %s", line);
  29. }
  30. hideProgress();
  31. debug("===== Done =====");
  32. }
  33. // Upload data to RTDB.
  34. boolean uploadData(
  35. float temperature,
  36. float pressure,
  37. float humidity,
  38. float light
  39. ) {
  40. showProgress(PROGRESS_GREEN);
  41. String data = String("{")
  42. + "\t\"temperature\": " + temperature + ",\n"
  43. + "\t\"pressure\": " + pressure + ",\n"
  44. + "\t\"humidity\": " + humidity + ",\n"
  45. + "\t\"light\": " + light + ",\n"
  46. + "\t\"time\": { \".sv\": \"timestamp\" }\n"
  47. + "}";
  48. debugln("Content body: ", data);
  49. String content = String("POST ") + RTDB_URL + " HTTP/1.1\r\n"
  50. + "Host: " + RTDB_HOST + "\r\n"
  51. + "User-Agent: ESP32/FunHouse/tarka-outdoor-weather-station" + "\r\n"
  52. + "Content-Type: application/x-www-form-urlencoded" + "\r\n"
  53. + "Accept: */*" + "\r\n"
  54. + "Content-Length: " + data.length() + "\r\n"
  55. + "Connection: close" + "\r\n"
  56. + "\r\n"
  57. + data;
  58. debugln("HTTP request: ", content);
  59. WiFiClientSecure client;
  60. client.setInsecure();
  61. showProgress(PROGRESS_GREEN);
  62. debugln("Connectiong to: ", RTDB_HOST);
  63. if(!client.connect(RTDB_HOST.c_str(), PORT)) {
  64. debug("Connection failed!");
  65. showError();
  66. return false;
  67. }
  68. debug("Connection established. Sending headers & body.");
  69. showProgress(PROGRESS_GREEN);
  70. client.print(content);
  71. // Wait for things to happen
  72. showProgress(PROGRESS_GREEN);
  73. delay(500);
  74. while(client.available()) {
  75. showProgress(PROGRESS_GREEN);
  76. String line = client.readStringUntil('\n');
  77. debugln("Read line: ", line);
  78. }
  79. debug("===== Done =====");
  80. hideProgress();
  81. return true;
  82. }