Working with MQTT up to Grafana

This commit is contained in:
Amritanshu Agrawal 2023-07-14 08:56:02 +05:30
parent f20d25ffb6
commit 83a5171fb6

View File

@ -1,6 +1,6 @@
#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 <PubSubClient.h> #include <PubSubClient.h>
#include <Wire.h> #include <Wire.h>
@ -9,41 +9,24 @@ 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;
// MQTT broker's address and port // MQTT settings
const char* mqttServer = "iot.tanshu.com"; const char* mqttServer = "iot.tanshu.com";
const int mqttPort = 1883; const int mqttPort = 1883;
const char* mqttClientId = "s3-roy";
// MQTT broker username and password
const char* mqttUser = "esp8266"; const char* mqttUser = "esp8266";
const char* mqttPassword = "esp8266"; const char* mqttPassword = "esp8266";
// DHT sensor pin // DHT sensor pin
const int dhtPin = D4; const int dhtPin = D4;
// Device name
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 setupWiFi(); void setupWiFi();
void connectToMQTT(); void connectToMQTT();
void sendSensorData(float temperature, float humidity, unsigned long timestamp, const char* device); void sendSensorData(float temperature, float humidity, const char* device);
void sendBufferedData();
// Data buffer
struct SensorData {
float temperature;
float humidity;
unsigned long timestamp;
};
const int BUFFER_SIZE = 10;
SensorData buffer[BUFFER_SIZE];
int bufferIndex = 0;
unsigned long previousTimestamp = 0;
const unsigned long interval = 30000; const unsigned long interval = 30000;
WiFiClient espClient; WiFiClient espClient;
@ -66,14 +49,18 @@ void loop() {
return; return;
} }
unsigned long currentTimestamp = millis(); if (!client.connected()) {
connectToMQTT();
}
client.loop();
if (currentTimestamp - previousTimestamp >= interval) {
float temperature = dht.readTemperature(); float temperature = dht.readTemperature();
float humidity = dht.readHumidity(); float humidity = dht.readHumidity();
if (isnan(temperature) || isnan(humidity)) { if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!"); Serial.println("Failed to read from DHT sensor!");
delay(1000);
return; return;
} }
@ -83,25 +70,10 @@ void loop() {
Serial.print(humidity); Serial.print(humidity);
Serial.println(" %"); Serial.println(" %");
// Buffer the data // Send the data
buffer[bufferIndex].temperature = temperature; sendSensorData(temperature, humidity, mqttClientId);
buffer[bufferIndex].humidity = humidity;
buffer[bufferIndex].timestamp = currentTimestamp;
// Increment the buffer index delay(interval); // Delay between readings
bufferIndex = (bufferIndex + 1) % BUFFER_SIZE;
// Attempt to send buffered data when connectivity is restored
sendBufferedData();
previousTimestamp = currentTimestamp;
}
if (!client.connected()) {
connectToMQTT();
}
client.loop();
} }
void setupWiFi() { void setupWiFi() {
@ -125,11 +97,11 @@ void setupWiFi() {
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, const char* device) {
char topic[50]; char topic[50];
snprintf(topic, sizeof(topic), "sensor/%s", device); snprintf(topic, sizeof(topic), "sensor/%s", device);
char payload[100]; char payload[100];
snprintf(payload, sizeof(payload), "{\"temperature\":%.2f,\"humidity\":%.2f,\"age\":%lu}", temperature, humidity, millis() - age); snprintf(payload, sizeof(payload), "{\"temperature\":%.2f,\"humidity\":%.2f}", temperature, humidity);
client.publish(topic, payload); client.publish(topic, payload);
Serial.println("Sent sensor data to MQTT broker!"); Serial.println("Sent sensor data to MQTT broker!");
} }
@ -138,7 +110,7 @@ void connectToMQTT() {
while (!client.connected()) { while (!client.connected()) {
Serial.print("Connecting to MQTT broker..."); Serial.print("Connecting to MQTT broker...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword)) { if (client.connect(mqttClientId, mqttUser, mqttPassword)) {
Serial.println("connected"); Serial.println("connected");
} else { } else {
Serial.print("failed, rc="); Serial.print("failed, rc=");
@ -148,24 +120,3 @@ void connectToMQTT() {
} }
} }
} }
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;
// Attempt to send the data
sendSensorData(temperature, humidity, age, deviceName);
// Wait a short time before sending the next data
delay(100);
}
// Clear the buffer
bufferIndex = 0;
}
}