#include <SoftwareSerial.h>
SoftwareSerial espSerial(51, 52); // RX, TX for ESP8266
const char* wifiSSID = "green";
const char* wifiPassword = "green@123";
const char* serverURL = "https://www.example.com/webapi/aqmsp_datapush.php.php?locationkey=505&stationkey=1200";
void setup() {
Serial.begin(115200);
espSerial.begin(115200);
connectToWiFi();
}
void loop() {
// Read sensor data or gather information you want to send
int ch1Value = 30;
int ch2Value = 40;
String jsonData = "{"ch1": " + String(ch1Value) + ", "ch2": " + String(ch2Value) + "}";+
// Send data to the API server
bool success = sendDataToServer(jsonData);
if (!success) {
Serial.println("Sending data failed. Retrying...");
resetAndRetry();
}
delay(5000); // Wait for 5 seconds before sending data again
}
void connectToWiFi() {
// Connect to your Wi-Fi network
Serial.println("Connecting to Wi-Fi...");
espSerial.println("AT+CWJAP="" + String(wifiSSID) + "","" + String(wifiPassword) + """);
delay(5000); // Wait for ESP8266 to connect to Wi-Fi
// Check if the Wi-Fi connection was successful
if (espSerial.find("OK")) {
Serial.println("Connected to Wi-Fi!");
} else {
Serial.println("Wi-Fi connection failed. Retrying...");
resetAndRetry();
}
}
bool sendDataToServer(String data) {
// Establish connection to your API server using the domain name
Serial.println("Connecting to server...");
espSerial.println("AT+CIPSTART="TCP","www.example.com",80");
delay(2000); // Wait for connection to be established
// Check if the server connection was successful
if (espSerial.find("OK")) {
Serial.println("Connected to server!");
} else {
Serial.println("Server connection failed. Retrying...");
resetAndRetry();
return false;
}
// Send HTTP POST request to your API server
String request = "POST " + String(serverURL) + " HTTP/1.1\r\n";
request += "Host: www.example.com\r\n";
request += "Content-Type: application/json\r\n";
request += "Content-Length: " + String(data.length()) + "\r\n\r\n";
request += data;
espSerial.print("AT+CIPSEND=");
espSerial.println(request.length());
delay(500); // Wait for module to prepare for data transmission
espSerial.println(request);
delay(2000); // Wait for data to be sent
// Check if the data was sent successfully
if (espSerial.find("SEND OK")) {
Serial.println("Data sent successfully!");
return true;
} else {
Serial.println("Data sending failed. Retrying...");
resetAndRetry();
return false;
}
}
void resetAndRetry() {
// Reset ESP8266 and retry the connection
espSerial.println("AT+RST");
delay(5000); // Wait for ESP8266 to restart
connectToWiFi(); // Attempt to connect to Wi-Fi and server again
}