Using multi wifi and fully working using secureclient

This commit is contained in:
Amritanshu Agrawal 2023-07-11 17:15:27 +05:30
parent 496ba9510a
commit 0ce1b6c557

View File

@ -1,17 +1,13 @@
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h> // Include the Wi-Fi-Multi library
#include <DHT.h> #include <DHT.h>
#include <Wire.h> #include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h> // Include the Wi-Fi-Multi library
#include <WiFiClientSecure.h> #include <WiFiClientSecure.h>
#include <Wire.h>
// ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti' ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'
// WiFi connect timeout per AP. Increase when connecting takes longer. // WiFi connect timeout per AP. Increase when connecting takes longer.
// const uint32_t connectTimeoutMs = 5000; const uint32_t connectTimeoutMs = 5000;
// Replace with your network credentials
const char* ssid = "Tanshu";
const char* password = "openwrt15";
// Replace with your server's address // Replace with your server's address
const char* serverAddress = "sensors.tanshu.com"; const char* serverAddress = "sensors.tanshu.com";
@ -21,21 +17,21 @@ const int serverPort = 443;
const int dhtPin = D4; const int dhtPin = D4;
// Replace with your device name // Replace with your device name
const char* deviceName = "s1-orb"; const char* deviceName = "s1-gwb";
// Initialize the DHT sensor // Initialize the DHT sensor
DHT dht(dhtPin, DHT22); DHT dht(dhtPin, DHT22);
// Function declaration // Function declaration
void connectToWiFi(); void setupWiFi();
void sendSensorData(float temperature, float humidity, unsigned long timestamp, const char* device); void sendSensorData(float temperature, float humidity, unsigned long timestamp, const char* device);
void sendBufferedData(); void sendBufferedData();
// Data buffer // Data buffer
struct SensorData { struct SensorData {
float temperature; float temperature;
float humidity; float humidity;
unsigned long timestamp; unsigned long timestamp;
}; };
const int BUFFER_SIZE = 10; const int BUFFER_SIZE = 10;
@ -46,135 +42,124 @@ unsigned long previousTimestamp = 0;
const unsigned long interval = 30000; const unsigned long interval = 30000;
void setup() { void setup() {
Serial.begin(9600); Serial.begin(9600);
// Serial.setDebugOutput(true);
connectToWiFi();
dht.begin(); setupWiFi();
dht.begin();
} }
void loop() { void loop() {
unsigned long currentTimestamp = millis(); // Maintain WiFi connection
if (wifiMulti.run(connectTimeoutMs) != WL_CONNECTED) {
if (currentTimestamp - previousTimestamp >= interval) { Serial.print(".");
float temperature = dht.readTemperature(); return;
float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
} }
Serial.print("Temperature: "); unsigned long currentTimestamp = millis();
Serial.print(temperature);
Serial.print(" °C\tHumidity: ");
Serial.print(humidity);
Serial.println(" %");
// Buffer the data if (currentTimestamp - previousTimestamp >= interval) {
buffer[bufferIndex].temperature = temperature; float temperature = dht.readTemperature();
buffer[bufferIndex].humidity = humidity; float humidity = dht.readHumidity();
buffer[bufferIndex].timestamp = currentTimestamp;
// Increment the buffer index if (isnan(temperature) || isnan(humidity)) {
bufferIndex = (bufferIndex + 1) % BUFFER_SIZE; Serial.println("Failed to read from DHT sensor!");
return;
}
// Attempt to send buffered data when connectivity is restored Serial.print("Temperature: ");
sendBufferedData(); Serial.print(temperature);
Serial.print(" °C\tHumidity: ");
Serial.print(humidity);
Serial.println(" %");
previousTimestamp = currentTimestamp; // Buffer the data
} buffer[bufferIndex].temperature = temperature;
buffer[bufferIndex].humidity = humidity;
buffer[bufferIndex].timestamp = currentTimestamp;
// Increment the buffer index
bufferIndex = (bufferIndex + 1) % BUFFER_SIZE;
// Attempt to send buffered data when connectivity is restored
sendBufferedData();
previousTimestamp = currentTimestamp;
}
} }
void connectToWiFi() { void setupWiFi() {
delay(2000); Serial.println("Setting up WiFi Connection");
Serial.println("Starting WiFi Connection");
// Set in station mode // Set in station mode
// WiFi.mode(WIFI_STA); WiFi.mode(WIFI_STA);
WiFi.setPhyMode(WIFI_PHY_MODE_11G);
// Register multi WiFi networks // Register multi WiFi networks
// wifiMulti.addAP("Tanshu", "openwrt15"); wifiMulti.addAP("Tanshu", "openwrt15");
WiFi.setPhyMode(WIFI_PHY_MODE_11G); wifiMulti.addAP("Mozimo", "bestchocever");
WiFi.begin(ssid, password);
// while (wifiMulti.run() != WL_CONNECTED) { while (wifiMulti.run(connectTimeoutMs) != WL_CONNECTED) {
while (WiFi.status() != WL_CONNECTED) { Serial.print(".");
delay(500); }
Serial.print(".");
}
Serial.println(""); Serial.println("");
Serial.print("Connected to "); Serial.print("Connected to ");
Serial.println(WiFi.SSID()); // Tell us what network we're connected to Serial.println(WiFi.SSID()); // Tell us what network we're connected to
Serial.println("IP address: " + WiFi.localIP().toString()); Serial.println("IP address: " + WiFi.localIP().toString());
} }
void sendSensorData(float temperature, float humidity, unsigned long age, const char* device) { void sendSensorData(float temperature, float humidity, unsigned long age, const char* device) {
String url = "/upload"; String url = "/upload";
WiFiClientSecure client; WiFiClientSecure client;
client.setInsecure();//skip verification client.setInsecure(); // skip verification
if (!client.connect(serverAddress, serverPort)) { if (!client.connect(serverAddress, serverPort)) {
Serial.println("Failed to connect to server!"); Serial.println("Failed to connect to server!");
return; return;
}
// if (client.verifyCertChain(serverAddress)) {
// Serial.println("Certificate matches!");
// } else {
// Serial.println("Certificate doesn't match!");
// }
// Calculate the length of the payload
String payload = "temp=" + String(temperature) + "&humidity=" + String(humidity) + "&age=" + String(millis() - age) + "&device=" + device;
int payloadLength = payload.length();
Serial.println("POST " + url + " HTTP/1.1\r\n" +
"Host: " + String(serverAddress) + "\r\n" +
"Connection: close\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + String(payloadLength) + "\r\n\r\n" +
payload);
client.print("POST " + url + " HTTP/1.1\r\n" +
"Host: " + String(serverAddress) + "\r\n" +
"Connection: close\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + String(payloadLength) + "\r\n\r\n" +
payload);
while (client.connected()) {
if (client.available()) {
String line = client.readStringUntil('\n');
Serial.println(line);
} }
}
Serial.println("Sent sensor data to server!"); // Calculate the length of the payload
String payload = "temp=" + String(temperature) + "&humidity=" + String(humidity) + "&age=" + String(millis() - age) + "&device=" + device;
int payloadLength = payload.length();
client.stop(); client.print("POST " + url + " HTTP/1.1\r\n" +
"Host: " + String(serverAddress) + "\r\n" +
"Connection: close\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n" +
"Content-Length: " + String(payloadLength) + "\r\n\r\n" +
payload);
while (client.connected()) {
if (client.available()) {
String line = client.readStringUntil('\n');
Serial.println(line);
}
}
Serial.println("Sent sensor data to server!");
client.stop();
} }
void sendBufferedData() { void sendBufferedData() {
if (WiFi.status() == WL_CONNECTED) { if (WiFi.status() == WL_CONNECTED) {
// Send buffered data if connectivity is restored // Send buffered data if connectivity is restored
for (int dataIndex = bufferIndex - 1; dataIndex >= 0; dataIndex--) { for (int dataIndex = bufferIndex - 1; dataIndex >= 0; dataIndex--) {
// Extract temperature, humidity, and timestamp from the buffer // Extract temperature, humidity, and timestamp from the buffer
float temperature = buffer[dataIndex].temperature; float temperature = buffer[dataIndex].temperature;
float humidity = buffer[dataIndex].humidity; float humidity = buffer[dataIndex].humidity;
unsigned long age = buffer[dataIndex].timestamp; unsigned long age = buffer[dataIndex].timestamp;
// Attempt to send the data // Attempt to send the data
// Serial.println("temp: " + String(temperature) + " // humidity: " + String(humidity) + " // age: " + String(millis() - age) + " // device: " + deviceName); sendSensorData(temperature, humidity, age, deviceName);
sendSensorData(temperature, humidity, age, deviceName);
// Wait a short time before sending the next data // Wait a short time before sending the next data
delay(100); delay(100);
}
// Clear the buffer
bufferIndex = 0;
} }
// Clear the buffer
bufferIndex = 0;
}
} }