2

I'm working with google Iot cloud with ESP32, I am sending fake values just to make a test with the MQTT data PUB/SUB, Apparently I'm succeeding in publishing the values, sometimes, I can't reconnect to google iot. I don't know why it keeps checking wifi...publising and doest check for the JWT key.

I have noticed that if I connect once to the google iot and then I unplug the esp32 from my pc (disconnect no power), and plug it back again and try to connect, I will enter in this "checking wifi" for about 30m, until I can connect back to google iot. How can fix this?

I beleived there was something to deal with this:

// Time (seconds) to expire token += 20 minutes for drift
const int jwt_exp_secs = 3600; // Maximum 24H (3600*24)

When I manage to get a good response that send info to the servers, i get this+:

entry 0x400806b8
Setup.....
Starting wifi
Connecting to WiFi
Connected
Waiting on time sync...
checking wifi...
connecting...Refreshing JWT
connected

Library connected!
incoming: /devices/esp32-device/config - 
incoming: /devices/esp32-device/config - 
Publishing value
Publishing value
Publishing value
Publishing value
Publishing value

There is times that I get a bad response for about 30m, using the same code, it seems to be sending constant data, which shouldn't be constant.(wasn't suppose to happen):

ho 0 tail 12 room 4
load:0x40080400,len:6352
entry 0x400806b8
Setup.....
Starting wifi
Connecting to WiFi
Connected
Waiting on time sync...
checking wifi...Publishing value
checking wifi...checking wifi...checking wifi...Publishing value
(Just keeps repeating)

This is the main connection to MQTT code, with the attempts to fix problems, but didn't work:

// This file contains static methods for API requests using Wifi / MQTT
#ifndef __ESP32_MQTT_H__
#define __ESP32_MQTT_H__
#include <Client.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <MQTT.h>
#include <CloudIoTCore.h> 
#include <CloudIoTCoreMqtt.h>
#include "ciotc_config.h" // Update this file with your configuration

void messageReceived(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
}


// Initialize WiFi and MQTT for this board
Client *netClient;
CloudIoTCoreDevice *device;
CloudIoTCoreMqtt *mqtt;
MQTTClient *mqttClient;
unsigned long iat = 0;
String jwt;

String getDefaultSensor() {
return  "Wifi: " + String(WiFi.RSSI()) + "db";
}

String getJwt() {
Serial.println("Entered JWT");
delay(5000);
iat = time(nullptr);
Serial.println("Refreshing JWT");
jwt = device->createJWT(iat, jwt_exp_secs);
return jwt;
}

void setupWifi() { 
Serial.println("Starting wifi");

Serial.print("WIFI status = ");
Serial.println(WiFi.getMode());
WiFi.disconnect(true);
delay(3000);
WiFi.mode(WIFI_STA);
delay(3000);
Serial.print("WIFI status = ");
Serial.println(WiFi.getMode());

WiFi.begin(ssid, password);
Serial.println("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
  delay(100);
 }
Serial.println("Connected");
delay(5000);

configTime(0, 0, ntp_primary, ntp_secondary);
Serial.println("Waiting on time sync...");
while (time(nullptr) < 1510644967) {
  delay(10);
}
}


void connectWifi() {
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
 Serial.print(".");
}
delay(5000);
}


bool publishTelemetry(String data) {
return mqtt->publishTelemetry(data);
}

 bool publishTelemetry(const char* data, int length) {
 return mqtt->publishTelemetry(data, length);
 }

 bool publishTelemetry(String subfolder, String data) {
 return mqtt->publishTelemetry(subfolder, data);
 } 

 bool publishTelemetry(String subfolder, const char* data, int length) {
 return mqtt->publishTelemetry(subfolder, data, length);
 }

 void connect() {
 connectWifi();
  mqtt->mqttConnect();

  delay(5000);
 }

 void setupCloudIoT() {
 device = new CloudIoTCoreDevice(
  project_id, location, registry_id, device_id,
  private_key_str);

 setupWifi();
 netClient = new WiFiClientSecure();
 mqttClient = new MQTTClient(512);
 mqttClient->setOptions(180, true, 1000); // keepAlive, cleanSession, timeout
 mqtt = new CloudIoTCoreMqtt(mqttClient, netClient, device);
 mqtt->setUseLts(true);
 mqtt->startMQTT();

 delay(5000);
 }
 #endif //__ESP32_MQTT_H__

This is the main.cpp:

#include <Arduino.h>
#include <WiFiClientSecure.h>
#include "esp32-mqtt.h"
#include <ArduinoJson.h>
#define led 14

char buffer[100];
float counter = 0;
float counter1 = 0;

void setup() {
Serial.begin(115200);

Serial.println("Setup.....");
pinMode(led, OUTPUT);

setupCloudIoT();
}

unsigned long lastMillis = 0;

void loop() {
mqtt->loop();
delay(10);  // <- fixes some issues with WiFi stability

if (!mqttClient->connected()) {
connect();
}

counter++;
counter1++;

if (millis() - lastMillis > 1000) {
Serial.println("Publishing value");
lastMillis = millis();
float temp = counter;
float hum = counter1;
StaticJsonDocument<100> doc;
doc["temp"] = temp;
doc["humidity"] = hum;
serializeJson(doc, buffer);
publishTelemetry(buffer);
}
}

Does someone know if there is any other module that doesn't have this same issue?

Nilton Schumacher F
  • 814
  • 3
  • 13
  • 43
  • Have you looked at the contents of `buffer` before you publish it? Is it correct? – romkey May 06 '20 at 05:26
  • Where can I look that? So strange getting 2 types of output – Nilton Schumacher F May 06 '20 at 05:28
  • It keeps checking wifi..publishing but it doesn't check for JWT, my wifi is all good. – Nilton Schumacher F May 06 '20 at 05:41
  • We'll probably need more of the code to help diagnose. It could also just be the particular board you're using (potentially bad WiFi module on the board itself). Anytime I hit weird intermittent problems like this, I always try with one or two other boards just to be sure it's not the hardware. – Gabe Weiss May 06 '20 at 07:52
  • well you've just edited your question to have totally different code. Your old code put together JSON which it published. Your new code doesn't appear to ever try to publish anything and doesn't correspond with the errors you shared. There's no way we can help you if you completely change the code you're trying to debug. – romkey May 06 '20 at 16:11
  • The code is the same, this is just the MQTT connection. it's still my old code, but for esp32 connect to google iot, it has 3 different files that work together...2 of the files are there, the other one is private info to connect to google iot, which won't help! – Nilton Schumacher F May 06 '20 at 16:23
  • Okay. See the lines at the end of the second file you published: `serializeJson(doc, buffer); publishTelemetry(buffer);` - add `Serial.println(buffer);` between those two lines and you should see the JSON you're sending. What does that look like? – romkey May 06 '20 at 16:23
  • I will be updating my question, and posting how it looks. But I'm getting that checking wifi error again, I just switched to another esp32. So I don't think the board is the problem. – Nilton Schumacher F May 06 '20 at 16:29

1 Answers1

0

The issue you face is IMHO not a problem of your code or the MQTT-lib you use. There seems to be a problem in the ESP32 core package (1.04 has it still). See this collection of issues from github and some proposed work around, which in the end delay the problem but do not solve it.
Issue with MQTT collection of problems from 2018 till today
These are open issues regarding WiFi re/connection problems
A test case for provoking an error is linked from one of the post.
I use for identifying ESP32 specific problems the identical programm on an esp8266 with MQTT connection and there it runs for months.
The ESP32 people have the bad habit to leave issues uncommented open for month hopeing the stale bot closes them. So I just cited the open issues, if you search for closed issues you'll find some more) closed by stale bot and not by solution!

Codebreaker007
  • 2,911
  • 1
  • 10
  • 22
  • I tried adding a 10s delay between wifi "checking wifi", it woked for the first time, but it isn't working anymore – Nilton Schumacher F May 06 '20 at 21:13
  • Damn, what a boring error, was so hyped for getting this to work, but as I can see, not going to happen – Nilton Schumacher F May 06 '20 at 21:13
  • Do you know if the MKR1000 has this same issue? – Nilton Schumacher F May 07 '20 at 20:38
  • As I have no MKR1000 I can only rely on the results of a search and if you do it with "MKR1000 wifi MQTT error connect" yourself you will also find lot of problems/open issues.One thing all the persons state is that the code works flawless on the weaker board ESP8266. My personal guess from my 30+ years experience: The more powerfull a board is the less carefull most devs are in looking at resources. – Codebreaker007 May 08 '20 at 08:38