Advertisement
Guest User

ESP32C3 deep sleep temp logger

a guest
Apr 18th, 2024
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.44 KB | None | 0 0
  1. #include <WiFi.h>
  2. #include <SimplePgSQL.h>
  3. #include "time.h"
  4. #include <ESP32Time.h>
  5. ESP32Time rtc(0);  // offset in seconds, use 0 because NTP already offset
  6.  
  7. #include <OneWire.h>
  8. #include <DallasTemperature.h>
  9.  
  10. #define ONE_WIRE_BUS 2
  11. #define LED_BUILTIN 8
  12.  
  13. // Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
  14. OneWire oneWire(ONE_WIRE_BUS);
  15.  
  16. // Pass our oneWire reference to Dallas Temperature.
  17. DallasTemperature sensors(&oneWire);
  18.  
  19. RTC_DATA_ATTR int readingCnt = 0;
  20.  
  21. typedef struct {
  22.   float temp;
  23.   unsigned long   time;
  24. } sensorReadings;
  25.  
  26. #define maximumReadings 6 // The maximum number of readings that can be stored in the available space
  27. #define sleeptimeSecs   5 // Every 10-mins of sleep 10 x 60-secs
  28.  
  29. RTC_DATA_ATTR sensorReadings Readings[maximumReadings];
  30.  
  31. const char* ntpServer = "pool.ntp.org";
  32. const long gmtOffset_sec = -18000;  //Replace with your GMT offset (secs)
  33. const int daylightOffset_sec = 3600;   //Replace with your daylight offset (secs)
  34. int hours, mins, secs;
  35. float tempC;
  36. bool sent = false;
  37.  
  38. IPAddress PGIP(xxx,xxx,xxx,xxx);        // your PostgreSQL server IP
  39.  
  40. const char ssid[] = "xxxxxxx";      //  your network SSID (name)
  41. const char pass[] = "xxxxxxxxx";      // your network password
  42.  
  43. const char user[] = "xxxx";       // your database user
  44. const char password[] = "xxxx";   // your database password
  45. const char dbname[] = "xxxxxxxx";         // your database name
  46.  
  47.  
  48. int WiFiStatus;
  49. WiFiClient client;
  50.  
  51.  
  52. char buffer[1024];
  53. PGconnection conn(&client, 0, 1024, buffer);
  54.  
  55. char tosend[128];
  56. String tosendstr;
  57.  
  58.  
  59. #ifndef USE_ARDUINO_ETHERNET
  60. void checkConnection()
  61. {
  62.     int status = WiFi.status();
  63.     if (status != WL_CONNECTED) {
  64.         if (WiFiStatus == WL_CONNECTED) {
  65.             Serial.println("Connection lost");
  66.             WiFiStatus = status;
  67.         }
  68.     }
  69.     else {
  70.         if (WiFiStatus != WL_CONNECTED) {
  71.             Serial.println("Connected");
  72.             WiFiStatus = status;
  73.         }
  74.     }
  75. }
  76.  
  77. #endif
  78.  
  79. static PROGMEM const char query_rel[] = "\
  80. SELECT a.attname \"Column\",\
  81.  pg_catalog.format_type(a.atttypid, a.atttypmod) \"Type\",\
  82.  case when a.attnotnull then 'not null ' else 'null' end as \"null\",\
  83.  (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid) for 128)\
  84.   FROM pg_catalog.pg_attrdef d\
  85.   WHERE d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef) \"Extras\"\
  86. FROM pg_catalog.pg_attribute a, pg_catalog.pg_class c\
  87. WHERE a.attrelid = c.oid AND c.relkind = 'r' AND\
  88. c.relname = %s AND\
  89. pg_catalog.pg_table_is_visible(c.oid)\
  90. AND a.attnum > 0 AND NOT a.attisdropped\
  91.    ORDER BY a.attnum";
  92.  
  93. static PROGMEM const char query_tables[] = "\
  94. SELECT n.nspname as \"Schema\",\
  95.  c.relname as \"Name\",\
  96.  CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized view' WHEN 'i' THEN 'index' WHEN 'S' THEN 'sequence' WHEN 's' THEN 'special' WHEN 'f' THEN 'foreign table' END as \"Type\",\
  97.  pg_catalog.pg_get_userbyid(c.relowner) as \"Owner\"\
  98. FROM pg_catalog.pg_class c\
  99.     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace\
  100. WHERE c.relkind IN ('r','v','m','S','f','')\
  101.      AND n.nspname <> 'pg_catalog'\
  102.      AND n.nspname <> 'information_schema'\
  103.      AND n.nspname !~ '^pg_toast'\
  104.  AND pg_catalog.pg_table_is_visible(c.oid)\
  105. ORDER BY 1,2";
  106.  
  107. int pg_status = 0;
  108.  
  109. void doPg(void)
  110. {
  111.     char *msg;
  112.     int rc;
  113.     if (!pg_status) {
  114.         conn.setDbLogin(PGIP,
  115.             user,
  116.             password,
  117.             dbname,
  118.             "utf8");
  119.         pg_status = 1;
  120.         return;
  121.     }
  122.  
  123.     if (pg_status == 1) {
  124.         rc = conn.status();
  125.         if (rc == CONNECTION_BAD || rc == CONNECTION_NEEDED) {
  126.             char *c=conn.getMessage();
  127.             if (c) Serial.println(c);
  128.             pg_status = -1;
  129.         }
  130.         else if (rc == CONNECTION_OK) {
  131.             pg_status = 2;
  132.             Serial.println("Enter query");
  133.         }
  134.         return;
  135.     }
  136.     if (pg_status == 2) {
  137.         if (!Serial.available()) return;
  138.         char inbuf[128];
  139.         int n = Serial.readBytesUntil('\n',inbuf,127);
  140.         while (n > 0) {
  141.             if (isspace(inbuf[n-1])) n--;
  142.             else break;
  143.         }
  144.         inbuf[n] = 0;
  145.  
  146.         if (!strcmp(inbuf,"\\d")) {
  147.             if (conn.execute(query_tables, true)) goto error;
  148.             Serial.println("Working...");
  149.             pg_status = 3;
  150.             return;
  151.         }
  152.         if (!strncmp(inbuf,"\\d",2) && isspace(inbuf[2])) {
  153.             char *c=inbuf+3;
  154.             while (*c && isspace(*c)) c++;
  155.             if (!*c) {
  156.                 if (conn.execute(query_tables, true)) goto error;
  157.                 Serial.println("Working...");
  158.                 pg_status = 3;
  159.                 return;
  160.             }
  161.             if (conn.executeFormat(true, query_rel, c)) goto error;
  162.             Serial.println("Working...");
  163.             pg_status = 3;
  164.             return;
  165.         }
  166.  
  167.         if (!strncmp(inbuf,"exit",4)) {
  168.             conn.close();
  169.             Serial.println("Thank you");
  170.             pg_status = -1;
  171.             return;
  172.         }
  173.         if (conn.execute(inbuf)) goto error;
  174.         Serial.println("Working...");
  175.         pg_status = 3;
  176.     }
  177.     if (pg_status == 3) {
  178.         rc=conn.getData();
  179.         int i;
  180.         if (rc < 0) goto error;
  181.         if (!rc) return;
  182.         if (rc & PG_RSTAT_HAVE_COLUMNS) {
  183.             for (i=0; i < conn.nfields(); i++) {
  184.                 if (i) Serial.print(" | ");
  185.                 Serial.print(conn.getColumn(i));
  186.             }
  187.             Serial.println("\n==========");
  188.         }
  189.         else if (rc & PG_RSTAT_HAVE_ROW) {
  190.             for (i=0; i < conn.nfields(); i++) {
  191.                 if (i) Serial.print(" | ");
  192.                 msg = conn.getValue(i);
  193.                 if (!msg) msg=(char *)"NULL";
  194.                 Serial.print(msg);
  195.             }
  196.             Serial.println();
  197.         }
  198.         else if (rc & PG_RSTAT_HAVE_SUMMARY) {
  199.             Serial.print("Rows affected: ");
  200.             Serial.println(conn.ntuples());
  201.         }
  202.         else if (rc & PG_RSTAT_HAVE_MESSAGE) {
  203.             msg = conn.getMessage();
  204.             if (msg) Serial.println(msg);
  205.         }
  206.         if (rc & PG_RSTAT_READY) {
  207.             pg_status = 2;
  208.             Serial.println("Enter query");
  209.         }
  210.     }
  211.     return;
  212. error:
  213.     msg = conn.getMessage();
  214.     if (msg) Serial.println(msg);
  215.     else Serial.println("UNKNOWN ERROR");
  216.     if (conn.status() == CONNECTION_BAD) {
  217.         Serial.println("Connection is bad");
  218.         pg_status = -1;
  219.     }
  220. }
  221.  
  222. int i;
  223.  
  224.  
  225. void setup(void)
  226. {
  227.     pinMode(LED_BUILTIN, OUTPUT);
  228.     Serial.begin(115200);
  229.     if ((readingCnt == 0)) {
  230.         WiFi.begin((char *)ssid, pass);
  231.         while (WiFi.status() != WL_CONNECTED) {
  232.             delay(250);
  233.         }
  234.         configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  235.        
  236.         struct tm timeinfo;
  237.         getLocalTime(&timeinfo);
  238.         rtc.setTimeStruct(timeinfo);
  239.         delay(250);
  240.       }
  241.     sensors.begin();
  242.  
  243.       digitalWrite(LED_BUILTIN, HIGH);
  244.       sensors.requestTemperatures();
  245.       tempC = sensors.getTempCByIndex(0);
  246.       Readings[readingCnt].temp = tempC;       // Units °C
  247.       Readings[readingCnt].time = rtc.getEpoch();
  248.       digitalWrite(LED_BUILTIN, LOW);        
  249.       delay(1000);
  250.       readingCnt++;
  251.  
  252.  
  253.  
  254.   if (readingCnt >= maximumReadings) {
  255.         WiFi.begin((char *)ssid, pass);
  256.         while (WiFi.status() != WL_CONNECTED) {
  257.             delay(250);
  258.         }
  259.         while (i<maximumReadings) {
  260.           checkConnection();
  261.           doPg();
  262.           if ((pg_status == 2) && (i<maximumReadings)){
  263.             tosendstr = "insert into burst values(24,1," + String(Readings[i].time) + "," + String(Readings[i].temp) + ")";
  264.             conn.execute(tosendstr.c_str());
  265.             pg_status = 3;
  266.             delay(50);
  267.             i++;
  268.           }
  269.           delay(50);
  270.         }
  271.   }
  272.     if (readingCnt < maximumReadings) {
  273.       esp_sleep_enable_timer_wakeup(sleeptimeSecs * 1000000);
  274.     esp_deep_sleep_start();
  275.     }
  276. }
  277.  
  278.  
  279. void loop()
  280. {
  281.  
  282.     checkConnection();
  283. doPg();
  284. /*if ((pg_status == 2) && (i<maximumReadings)){
  285.     tosendstr = "insert into burst values(24,1," + String(Readings[i].time) + "," + String(Readings[i].temp) + ")";
  286.     conn.execute(tosendstr.c_str());
  287.     pg_status = 3;
  288.     delay(50);
  289.     i++;
  290.   }*/
  291. delay(50);
  292. }
  293.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement