Sending MQTT Data

This commit is contained in:
Amritanshu Agrawal 2023-07-13 06:56:47 +05:30
parent 0ce1b6c557
commit f20d25ffb6
2 changed files with 40 additions and 33 deletions

View File

@ -15,3 +15,4 @@ framework = arduino
lib_deps = lib_deps =
adafruit/DHT sensor library@^1.4.4 adafruit/DHT sensor library@^1.4.4
adafruit/Adafruit Unified Sensor@^1.1.9 adafruit/Adafruit Unified Sensor@^1.1.9
knolleary/PubSubClient@^2.8

View File

@ -1,7 +1,7 @@
#include <DHT.h> #include <DHT.h>
#include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h> // Include the Wi-Fi-Multi library #include <ESP8266WiFiMulti.h> // Include the Wi-Fi-Multi library
#include <WiFiClientSecure.h> #include <PubSubClient.h>
#include <Wire.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'
@ -9,14 +9,18 @@ ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class
// 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 server's address // MQTT broker's address and port
const char* serverAddress = "sensors.tanshu.com"; const char* mqttServer = "iot.tanshu.com";
const int serverPort = 443; const int mqttPort = 1883;
// Replace with your DHT sensor pin // MQTT broker username and password
const char* mqttUser = "esp8266";
const char* mqttPassword = "esp8266";
// DHT sensor pin
const int dhtPin = D4; const int dhtPin = D4;
// Replace with your device name // Device name
const char* deviceName = "s1-gwb"; const char* deviceName = "s1-gwb";
// Initialize the DHT sensor // Initialize the DHT sensor
@ -24,6 +28,7 @@ DHT dht(dhtPin, DHT22);
// Function declaration // Function declaration
void setupWiFi(); void setupWiFi();
void connectToMQTT();
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();
@ -41,12 +46,17 @@ int bufferIndex = 0;
unsigned long previousTimestamp = 0; unsigned long previousTimestamp = 0;
const unsigned long interval = 30000; const unsigned long interval = 30000;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() { void setup() {
Serial.begin(9600); Serial.begin(9600);
setupWiFi(); setupWiFi();
dht.begin(); dht.begin();
client.setServer(mqttServer, mqttPort);
} }
void loop() { void loop() {
@ -86,6 +96,12 @@ void loop() {
previousTimestamp = currentTimestamp; previousTimestamp = currentTimestamp;
} }
if (!client.connected()) {
connectToMQTT();
}
client.loop();
} }
void setupWiFi() { void setupWiFi() {
@ -110,37 +126,27 @@ void setupWiFi() {
} }
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"; char topic[50];
snprintf(topic, sizeof(topic), "sensor/%s", device);
char payload[100];
snprintf(payload, sizeof(payload), "{\"temperature\":%.2f,\"humidity\":%.2f,\"age\":%lu}", temperature, humidity, millis() - age);
client.publish(topic, payload);
Serial.println("Sent sensor data to MQTT broker!");
}
WiFiClientSecure client; void connectToMQTT() {
client.setInsecure(); // skip verification while (!client.connected()) {
Serial.print("Connecting to MQTT broker...");
if (!client.connect(serverAddress, serverPort)) { if (client.connect("ESP8266Client", mqttUser, mqttPassword)) {
Serial.println("Failed to connect to server!"); Serial.println("connected");
return; } else {
} Serial.print("failed, rc=");
Serial.print(client.state());
// Calculate the length of the payload Serial.println(" retrying in 5 seconds");
String payload = "temp=" + String(temperature) + "&humidity=" + String(humidity) + "&age=" + String(millis() - age) + "&device=" + device; delay(5000);
int payloadLength = payload.length();
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() {