Google iot MQTT - ESP32 Connects the first time and only reconnects after 30m

烈酒焚心 提交于 2020-05-16 22:34:45

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/61627725/google-iot-mqtt-esp32-connects-the-first-time-and-only-reconnects-after-30m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!