Advertisement
mudhita_triari

Untitled

Jun 24th, 2024
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.55 KB | None | 0 0
  1. #include <Arduino.h>
  2. #include <WiFi.h>
  3. #include <WiFiMulti.h>
  4. #include <WiFiManager.h>
  5. #include <HTTPClient.h>
  6. #include <ArduinoJson.h>
  7. #include <otadrive_esp.h>
  8.  
  9. WiFiManager wm;
  10.  
  11. // Server details
  12. const char* serverName = "https://bootcampindobot.com/index_mudhita1.php";
  13. const char* apiKeyValue = "tPmAT5Ab3j7F9";
  14.  
  15. // UART communication settings
  16. const int SERIAL_BAUD_RATE = 115200;
  17. const int SERIAL_RX_PIN = 16;
  18. const int SERIAL_TX_PIN = 17;
  19.  
  20. // WiFiMulti instance
  21. WiFiMulti wifiMulti;
  22.  
  23. // HardwareSerial instance for UART2
  24. HardwareSerial SerialESP32_7(2);
  25.  
  26. String FW_VERSION = "1.0.4";
  27.  
  28. unsigned long previousSyncMillis = 0;
  29. const long syncInterval = 60000; // Sync every 60 seconds
  30.  
  31. // LED pin
  32. const int LED_PIN = 2; // Ganti dengan pin yang sesuai untuk LED
  33.  
  34. // Function prototypes
  35. void saveWifiCallback();
  36. void configModeCallback(WiFiManager *myWiFiManager);
  37. void onUpdateProgress(int progress, int total);
  38. void sync_task();
  39. void sendDataOverUART(const char* chipId, const char* tempOffset, const char* humOffset, const char* ppmOffset,
  40. const char* luxOffset, const char* longitude, const char* latitude, const char* elevation);
  41. void sendHttpPost(const char* id, float hum, float temp, float ppm, float lux, float longitude, float latitude, float elevation);
  42. void printAligned(const char* label, const char* value);
  43. void logData(const char* label, float value);
  44. void logData(const char* label, const char* value);
  45. void blinkLED(int times, int duration);
  46.  
  47. void setup() {
  48. // Inisialisasi pin LED
  49. pinMode(LED_PIN, OUTPUT);
  50. digitalWrite(LED_PIN, LOW);
  51.  
  52. Serial.begin(SERIAL_BAUD_RATE);
  53. Serial.println("Starting setup...");
  54.  
  55. // Inisialisasi UART pada pin RX dan TX yang ditentukan
  56. SerialESP32_7.begin(SERIAL_BAUD_RATE, SERIAL_8N1, SERIAL_RX_PIN, SERIAL_TX_PIN);
  57.  
  58. // Enable debug output untuk WiFiManager
  59. wm.setDebugOutput(true);
  60.  
  61. // Tambahkan parameter custom untuk WiFiManager
  62. WiFiManagerParameter custom_id("id", "Device ID", "", 32);
  63. WiFiManagerParameter custom_hum("hum", "Humidity", "", 5);
  64. WiFiManagerParameter custom_temp("temp", "Temperature", "", 5);
  65. WiFiManagerParameter custom_ppm("ppm", "PPM", "", 5);
  66. WiFiManagerParameter custom_lux("lux", "Lux", "", 5);
  67. WiFiManagerParameter custom_longitude("longitude", "Longitude", "", 12);
  68. WiFiManagerParameter custom_latitude("latitude", "Latitude", "", 12);
  69. WiFiManagerParameter custom_elevation("elevation", "Elevation", "", 5);
  70.  
  71. // Tambahkan parameter ke WiFiManager
  72. wm.addParameter(&custom_id);
  73. wm.addParameter(&custom_hum);
  74. wm.addParameter(&custom_temp);
  75. wm.addParameter(&custom_ppm);
  76. wm.addParameter(&custom_lux);
  77. wm.addParameter(&custom_longitude);
  78. wm.addParameter(&custom_latitude);
  79. wm.addParameter(&custom_elevation);
  80.  
  81. // Set callback untuk WiFiManager
  82. wm.setAPCallback(configModeCallback);
  83. wm.setSaveConfigCallback(saveWifiCallback);
  84.  
  85. // Mulai konfigurasi WiFiManager portal
  86. if (!wm.autoConnect("ENVIRO OBSERVER DIAGNOSIS", "password")) {
  87. Serial.println("Failed to connect to WiFi and timeout");
  88. delay(3000);
  89. ESP.restart();
  90. }
  91.  
  92. Serial.println("Connected to WiFi");
  93.  
  94. // Kirim data melalui UART setelah terhubung
  95. sendDataOverUART(custom_id.getValue(), custom_hum.getValue(), custom_temp.getValue(), custom_ppm.getValue(),
  96. custom_lux.getValue(), custom_longitude.getValue(), custom_latitude.getValue(),
  97. custom_elevation.getValue());
  98.  
  99. // Periksa nilai parameter yang disimpan
  100. Serial.println("\n-----------------KALIBRASI NODEMESH-----------------\n");
  101. printAligned("Device ID:", custom_id.getValue());
  102. printAligned("Humidity:", custom_hum.getValue());
  103. printAligned("Temperature:", custom_temp.getValue());
  104. printAligned("PPM:", custom_ppm.getValue());
  105. printAligned("Lux:", custom_lux.getValue());
  106.  
  107. Serial.println("\n------------------LOKASI NODEMESH------------------\n");
  108. printAligned("Longitude:", custom_longitude.getValue());
  109. printAligned("Latitude:", custom_latitude.getValue());
  110. printAligned("Elevation:", custom_elevation.getValue());
  111.  
  112. Serial.println("Setup complete.");
  113. }
  114.  
  115. void loop() {
  116. if (SerialESP32_7.available()) {
  117. blinkLED(3, 100); // LED berkedip 3 kali saat data diterima
  118. String serialMsg = SerialESP32_7.readStringUntil('\n');
  119. serialMsg.trim();
  120.  
  121. Serial.println("Diterima dari Pusat Data: " + serialMsg);
  122.  
  123. if (serialMsg.length() > 0) {
  124. DynamicJsonDocument doc(256);
  125. DeserializationError error = deserializeJson(doc, serialMsg);
  126.  
  127. if (error) {
  128. Serial.print("deserializeJson() gagal: ");
  129. Serial.println(error.c_str());
  130. } else {
  131. const char* id = doc["id"];
  132. if (!id) {
  133. Serial.println("JSON tidak valid: 'id' tidak ditemukan");
  134. } else {
  135. if (doc.containsKey("hum") && doc.containsKey("temp") && doc.containsKey("ppm") && doc.containsKey("lux") &&
  136. doc.containsKey("longitude") && doc.containsKey("latitude") && doc.containsKey("elevation")) {
  137. float hum = doc["hum"];
  138. float temp = doc["temp"];
  139. float ppm = doc["ppm"];
  140. float lux = doc["lux"];
  141. float longitude = doc["longitude"].as<float>();
  142. float latitude = doc["latitude"].as<float>();
  143. float elevation = doc["elevation"];
  144.  
  145. // Log data received from UART
  146. Serial.println("\nData diterima dari UART:");
  147. logData("ID:", id);
  148. logData("Kelembaban:", hum);
  149. logData("Suhu:", temp);
  150. logData("PPM:", ppm);
  151. logData("Lux:", lux);
  152. logData("Longitude:", longitude);
  153. logData("Latitude:", latitude);
  154. logData("Elevasi:", elevation);
  155.  
  156. // Send data to the server
  157. sendHttpPost(id, hum, temp, ppm, lux, longitude, latitude, elevation);
  158.  
  159. Serial.println("\nMengirim data berikut ke server:");
  160. logData("ID:", id);
  161. logData("UNIT:", id);
  162. logData("Kelembaban:", hum);
  163. logData("Suhu:", temp);
  164. logData("PPM:", ppm);
  165. logData("Lux:", lux);
  166. logData("Longitude:", longitude);
  167. logData("Latitude:", latitude);
  168. logData("Elevasi:", elevation);
  169. } else {
  170. Serial.println("JSON tidak valid: beberapa kunci data tidak ditemukan");
  171. }
  172. }
  173. }
  174. }
  175. }
  176. sync_task();
  177. }
  178.  
  179. void sync_task() {
  180. unsigned long currentMillis = millis();
  181. if (currentMillis - previousSyncMillis >= syncInterval) {
  182. previousSyncMillis = currentMillis;
  183.  
  184. if (WiFi.status() != WL_CONNECTED) {
  185. Serial.println("WiFi tidak terhubung! Mencoba menghubungkan kembali...");
  186. WiFi.reconnect();
  187. return;
  188. }
  189.  
  190. Serial.println("Firmware version: " + FW_VERSION);
  191. OTADRIVE.updateFirmware();
  192. }
  193. }
  194.  
  195. void sendDataOverUART(const char* chipId, const char* tempOffset, const char* humOffset, const char* ppmOffset,
  196. const char* luxOffset, const char* longitude, const char* latitude, const char* elevation) {
  197. StaticJsonDocument<200> jsonDocument;
  198.  
  199. jsonDocument["chipId"] = chipId;
  200. jsonDocument["tempOffset"] = tempOffset;
  201. jsonDocument["humOffset"] = humOffset;
  202. jsonDocument["ppmOffset"] = ppmOffset;
  203. jsonDocument["luxOffset"] = luxOffset;
  204. jsonDocument["longitude"] = longitude;
  205. jsonDocument["latitude"] = latitude;
  206. jsonDocument["elevation"] = elevation;
  207.  
  208. String jsonString;
  209. serializeJson(jsonDocument, jsonString);
  210.  
  211. SerialESP32_7.println(jsonString);
  212. }
  213.  
  214. void sendHttpPost(const char* id, float hum, float temp, float ppm, float lux, float longitude, float latitude, float elevation) {
  215. if (WiFi.status() == WL_CONNECTED) {
  216. blinkLED(2, 100); // LED berkedip 2 kali saat data dikirim
  217. HTTPClient http;
  218. http.begin(serverName);
  219.  
  220. http.addHeader("Content-Type", "application/x-www-form-urlencoded");
  221.  
  222. String httpRequestData = "api_key=" + String(apiKeyValue) + "&id=" + String(id) + "&hum=" + String(hum) +
  223. "&temp=" + String(temp) + "&ppm=" + String(ppm) + "&lux=" + String(lux) +
  224. "&longitude=" + String(longitude) + "&latitude=" + String(latitude) + "&elevation=" + String(elevation);
  225.  
  226. int httpResponseCode = http.POST(httpRequestData);
  227.  
  228. if (httpResponseCode > 0) {
  229. String response = http.getString();
  230. Serial.println("HTTP Response code: " + String(httpResponseCode));
  231. Serial.println("Response: " + response);
  232. } else {
  233. Serial.println("Error on sending POST: " + String(httpResponseCode));
  234. }
  235.  
  236. http.end();
  237. } else {
  238. Serial.println("WiFi Disconnected");
  239. }
  240. }
  241.  
  242. void saveWifiCallback() {
  243. Serial.println("Parameter WiFi tersimpan.");
  244. }
  245.  
  246. void configModeCallback(WiFiManager *myWiFiManager) {
  247. Serial.println("Entered configuration mode");
  248. Serial.println(WiFi.softAPIP());
  249. Serial.println(myWiFiManager->getConfigPortalSSID());
  250. }
  251.  
  252. void onUpdateProgress(int progress, int total) {
  253. int percentage = (progress * 100) / total;
  254. Serial.printf("Progress: %d%%\n", percentage);
  255. }
  256.  
  257. void printAligned(const char* label, const char* value) {
  258. Serial.print(label);
  259. int len = strlen(label) + strlen(value);
  260. for (int i = len; i < 40; i++) {
  261. Serial.print(" ");
  262. }
  263. Serial.println(value);
  264. }
  265.  
  266. void logData(const char* label, float value) {
  267. Serial.print(label);
  268. Serial.println(value);
  269. }
  270.  
  271. void logData(const char* label, const char* value) {
  272. Serial.print(label);
  273. Serial.println(value);
  274. }
  275.  
  276. void blinkLED(int times, int duration) {
  277. for (int i = 0; i < times; i++) {
  278. digitalWrite(LED_PIN, HIGH);
  279. delay(duration);
  280. digitalWrite(LED_PIN, LOW);
  281. delay(duration);
  282. }
  283. }
  284.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement