1
+ #include < Arduino.h>
2
+ #include " MHZ19.h"
3
+ #include < HardwareSerial.h>
4
+ #include < WiFi.h>
5
+ #include < ArduinoJson.h>
6
+ #include < HTTPClient.h>
7
+ #include < esp_wifi.h>
8
+ #include < vector>
9
+
10
+ #define BAUDRATE 9600 // Device to MH-Z19 Serial baudrate (should not be changed)
11
+ const char * ssid = " Wifi SSID" ; // WiFi SSID
12
+ const char * password = " WIFI PASSWORD" ; // WiFi Password
13
+ const char * api_url = " https://backend.thinger.io/v3/users/..." ; // Thinger.io host
14
+ const String token = " Bearer ABCABCABC" ;
15
+
16
+ MHZ19 myMHZ19; // Constructor for library
17
+ HardwareSerial mySerial (2 );
18
+ WiFiClientSecure client;
19
+
20
+ std::vector<String> offlineData;
21
+
22
+ unsigned long getDataTimer = 0 ;
23
+
24
+ void setup ()
25
+ {
26
+ Serial.begin (9600 ); // Device to serial monitor feedback
27
+
28
+ mySerial.begin (BAUDRATE);
29
+ myMHZ19.begin (mySerial); // *Serial(Stream) refence must be passed to library begin().
30
+ myMHZ19.autoCalibration (); // Turn auto calibration ON (OFF autoCalibration(false))
31
+
32
+ WiFi.mode (WIFI_STA);
33
+ WiFi.begin (ssid, password);
34
+ while (WiFi.status () != WL_CONNECTED) {
35
+ Serial.print (' .' );
36
+ delay (1000 );
37
+ }
38
+ Serial.println (WiFi.localIP ());
39
+ client.setInsecure ();
40
+ }
41
+
42
+ void sendData (String data) {
43
+ HTTPClient http;
44
+ http.begin (client, api_url);
45
+ http.addHeader (" Content-Type" , " application/json;charset=UTF-8" );
46
+ http.addHeader (" Authorization" , token);
47
+ int httpCode = http.POST (data);
48
+ if (httpCode != 200 && httpCode > 0 ) {
49
+ String payload = http.getString ();
50
+ Serial.println (httpCode);
51
+ Serial.println (payload);
52
+ }
53
+ else {
54
+ Serial.println (http.errorToString (httpCode).c_str ());
55
+ }
56
+ http.end ();
57
+ }
58
+
59
+ void loop ()
60
+ {
61
+ if (millis () - getDataTimer >= 61000 )
62
+ {
63
+ JsonDocument doc;
64
+ String data;
65
+
66
+ doc[" co2" ] = myMHZ19.getCO2 ();
67
+ doc[" temperature" ] = (int )myMHZ19.getTemperature ();
68
+ doc[" startup_time" ] = millis () / 1000 ;
69
+ serializeJson (doc, data);
70
+ if (WiFi.status () == WL_CONNECTED)
71
+ {
72
+ // if (offlineData.size() > 0) {
73
+ // for (auto& d : offlineData) {
74
+ // sleep(0.1);
75
+ // sendData(d);
76
+ // }
77
+ // offlineData.clear();
78
+ // }
79
+ // Send the current data
80
+ sendData (data);
81
+ } else {
82
+ // If WiFi is not connected, store the data for later
83
+ // if (offlineData.size() > 800) {
84
+ // offlineData.erase(offlineData.begin());
85
+ // }
86
+ offlineData.push_back (data);
87
+ WiFi.begin (ssid, password);
88
+ }
89
+ }
90
+ }
0 commit comments