Hi everyone,
So I have this basic setup as I wrote in the title.
I have this connecting via WiFi to my network and communicating via MQTT with my OpenHab2 installation where I have a lot more devices.
All works well with no conflicts, but something on my code here is not correct because after a couple of days, exactly at midnight it stops communicating and I have to restart the device. This makes no sense.
Can someone please help me here looking at my code?
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTPIN 13
#define DHTTYPE DHT11
int period = 200000; //Corre a cada 2 minutos
unsigned long time_now = 0;
int sensor_pin = A0;
int s;
char mensagem[100];
char* ssid = "BLA";
const char* password = "BLA";
const char* mqttServer = "1.2.3.4";
const int mqttPort = 1883;
const char* mqttUser = "DVES_USER";
const char* mqttPassword = "****";
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Iniciando conexao com a rede WiFi...");
}
Serial.println("Conectado na rede WiFi!");
dht.begin();
}
void loop() {
if(millis() - time_now > period){
time_now = millis();
float h = dht.readHumidity();
float t = dht.readTemperature();
s = analogRead(sensor_pin);
//Faz a conexao com o broker MQTT
reconectabroker();
sprintf(mensagem, "{\"Temperatura\":\"%d\",\"Humidade\":\"%d\",\"Solo\":\"%d\"}", (int)t, (int)h, (int)s);
Serial.println(mensagem);
//Envia a mensagem ao broker
client.publish("Sensor_Temp_Hum_Solo", mensagem);
}
}
void reconectabroker() {
//Conexao ao broker MQTT
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Conectando ao broker MQTT...");
if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
Serial.println("Conectado ao broker!");
} else {
Serial.print("Falha na conexao ao broker - Estado: ");
Serial.print(client.state());
delay(2000);
}
}
}
Thanks a lot in advance!
SOLUTION:
After a lot of trial and error, the problem that originated this topic was my old router from my previous ISP... >:(
Well, anyway, thanks to the kind help of people in this forum and also a lot of search that I've made, here's my perfectly working code going now more than 2 weeks always on and communicating without interuptions:
//Program: ESP32 Wifi module with sensors communicating via MQTT
//Author: Pedro Lima (MAIDOT)
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
#define DHTPIN 13
#define DHTTYPE DHT11
unsigned long period = 120000; //Runs each 2 minutes
unsigned long time_now = 0;
int sensor_soil_pin = A0;
int soil;
int soil_a;
const int sensor_rain_pin = 15;
int rain;
int rain_a;
char msg[100];
char* ssid = "HIDDEN";
const char* password = "HIDDEN";
const char* mqttServer = "192.168.1.100";
const int mqttPort = 1883;
const char* mqttUser = "DVES_USER";
const char* mqttPassword = "****";
IPAddress local_IP(192, 168, 2, 201);
IPAddress gateway(192, 168, 2, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);
WiFiClient espClient;
PubSubClient client(espClient);
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(115200);
WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
WiFi.setAutoReconnect(true);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Starting WiFi connection to the network...");
}
Serial.println("Connected to WiFi network!");
if(WiFi.getSleep() == true) {
WiFi.setSleep(false);
Serial.println("WiFi Sleep is now deactivated.");
}
dht.begin();
}
void loop() {
if ( WiFi.status() == WL_CONNECTED ){ //Connected to WiFi
if(millis() - time_now > period){ //Using ESP timer "esp_timer_get_time()" did not went well
time_now = millis();
//Serial.print("ESP time right now: ");
//Serial.println(time_now);
float h = dht.readHumidity();
float t = dht.readTemperature();
soil_a = analogRead(sensor_soil_pin);
rain_a = analogRead(sensor_rain_pin);
soil = map(soil_a, 0, 4095, 100, 0);
rain = map(rain_a, 0, 4095, 100, 0);
//Establishes a connection to MQTT broker
reconectabroker();
sprintf(msg, "{\"Temperature\":\"%d\",\"Humidity\":\"%d\",\"Soil\":\"%d\",\"Rain\":\"%d\"}", (int)t, (int)h, (int)soil, (int)rain);
Serial.println(msg);
//Send message to MQTT broker
client.publish("Sensors_THSR_Exterior", msg);
Serial.println("Message successfully sent to MQTT broker...");
}
}else{ //WiFi not connected, try to reconnect
WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
WiFi.begin();
int UpCount = 0;
int WLcount = 0;
Serial.println("Trying to reconnect to WiFi network...");
while (WiFi.status() != WL_CONNECTED && WLcount < 200 ){
delay( 100 );
Serial.printf(".");
if (UpCount >= 60){
UpCount = 0;
Serial.printf("\n");
}
++UpCount;
++WLcount;
}
if(WiFi.status() != WL_CONNECTED){
Serial.println("Impossible reconnecting to WiFi, rebooting device!");
ESP.restart();
}
}
}
void reconectabroker() {
//Connection to MQTT broker
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT broker...");
if (client.connect("ESP32Client", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT broker!");
} else {
Serial.print("Fail while connecting to MQTT broker - Status: ");
Serial.print(client.state());
delay(2000);
}
}
}