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