mobizt / Firebase-ESP32

[DEPRECATED]🔥 Firebase RTDB Arduino Library for ESP32. The complete, fast, secured and reliable Firebase Arduino client library that supports CRUD (create, read, update, delete) and Stream operations.
MIT License
413 stars 119 forks source link

Token error: code: -4, message: connection lost #302

Closed Nikitanagar closed 8 months ago

Nikitanagar commented 8 months ago

I am using the GSM with esp32 and this error shows:

Token info: type = id token (GITKit token), status = error Token error: code: -4, message: connection lost Token info: type = id token (GITKit token), status = on request Token info: type = id token (GITKit token), status = error Token error: code: -4, message: connection lost Token info: type = id token (GITKit token), status = on request

but with wifi, it is working fine.

mobizt commented 8 months ago

You should follow these examples and adapt it with your GSM module.

Nikitanagar commented 8 months ago

Yeah I use this example. Here's the code..

/**

/* This example shows the basic RTDB usage with TTGO T-A7670 (ESP32 with SIMCom SIMA7670) and TinyGSMClient. /

// To allow TinyGSM library integration, the following macro should be defined in src/ESP_Mail_FS.h or // your custom config file src/Custom_ESP_Mail_FS.h. // #define TINY_GSM_MODEM_SIM7600

define TINY_GSM_MODEM_SIM7600 // SIM7600 AT instruction is compatible with A7670

define SerialAT Serial1

define SerialMon Serial

define TINY_GSM_USE_GPRS true

include

include

//#include

include

include

include

include

include // SIMA7670 Compatible with SIM7600 AT instructions

// Set serial for debug console (to the Serial Monitor, default speed 115200)

define SerialMon Serial

// Set serial for AT commands (to the module) // Use Hardware Serial on Mega, Leonardo, Micro

define SerialAT Serial1

// See all AT commands, if wanted

ifdef DUMP_AT_COMMANDS

include

StreamDebugger debugger(SerialAT, SerialMon); TinyGsm modem(debugger);

else

TinyGsm modem(SerialAT);

endif

TinyGsmClient client(modem);

// Define the serial console for debug prints, if needed

define TINY_GSM_DEBUG SerialMon

define TINY_GSM_USE_GPRS true

define TINY_GSM_USE_WIFI false

// set GSM PIN, if any

define GSM_PIN ""

// Your GPRS credentials, if any const char apn[] = ""; const char gprsUser[] = ""; const char gprsPass[] = "";

define uS_TO_S_FACTOR 1000000ULL // Conversion factor for micro seconds to seconds

define TIME_TO_SLEEP 600 // Time ESP32 will go to sleep (in seconds)

define UART_BAUD 115200

define PIN_DTR 25

define PIN_TX 26

define PIN_RX 27

define PWR_PIN 4

define BAT_ADC 35

define BAT_EN 12

define PIN_RI 33

define PIN_DTR 25

define RESET 5

define SD_MISO 2

define SD_MOSI 15

define SD_SCLK 14

define SD_CS 13

include

include

TinyGsmClient gsm_client(modem);

// Provide the token generation process info.

include <addons/TokenHelper.h>

// Provide the RTDB payload printing info and other helper functions.

include <addons/RTDBHelper.h>

// For the following credentials, see examples/Authentications/SignInAsUser/EmailPassword/EmailPassword.ino

/ 1. Define the API Key /

define API_KEY "......."

/ 2. Define the RTDB URL /

define DATABASE_URL "......." //.firebaseio.com or ..firebasedatabase.app

/ 3. Define the user Email and password that alreadey registerd or added in your project /

define USER_EMAIL "........"

define USER_PASSWORD "........"

// Define Firebase Data object FirebaseData fbdo;

FirebaseAuth auth; FirebaseConfig config;

unsigned long sendDataPrevMillis = 0;

unsigned long count = 0;

void setup() {

Serial.begin(115200);

delay(10);
pinMode(BAT_EN, OUTPUT);
digitalWrite(BAT_EN, HIGH);

// A7670 Reset
pinMode(RESET, OUTPUT);
digitalWrite(RESET, LOW);
delay(100);
digitalWrite(RESET, HIGH);
delay(3000);
digitalWrite(RESET, LOW);

pinMode(PWR_PIN, OUTPUT);
digitalWrite(PWR_PIN, LOW);
delay(100);
digitalWrite(PWR_PIN, HIGH);
delay(1000);
digitalWrite(PWR_PIN, LOW);

DBG("Wait...");

delay(3000);

SerialAT.begin(UART_BAUD, SERIAL_8N1, PIN_RX, PIN_TX);

// Restart takes quite some time
// To skip it, call init() instead of restart()
DBG("Initializing modem...");
if (!modem.init())
{
    DBG("Failed to restart modem, delaying 10s and retrying");
    return;
}

/*
2 Automatic
13 GSM Only
14 WCDMA Only
38 LTE Only
*/
modem.setNetworkMode(38);
if (modem.waitResponse(10000L) != 1)
{
    DBG("setNetworkMode faill");
}

String name = modem.getModemName();
DBG("Modem Name:", name);

String modemInfo = modem.getModemInfo();
DBG("Modem Info:", modemInfo);

Serial_Printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);

/* Assign the api key (required) */
config.api_key = API_KEY;

/* Assign the user sign in credentials */
auth.user.email = USER_EMAIL;
auth.user.password = USER_PASSWORD;

/* Assign the RTDB URL (required) */
config.database_url = DATABASE_URL;

/* Assign the callback function for the long running token generation task */
config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h

fbdo.setGSMClient(&gsm_client, &modem, GSM_PIN, apn, gprsUser, gprsPass);

// Comment or pass false value when WiFi reconnection will control by your code or third party library e.g. WiFiManager
Firebase.reconnectNetwork(true);

// Since v4.4.x, BearSSL engine was used, the SSL buffer need to be set.
// Large data transmission may require larger RX buffer, otherwise connection issue or data read time out can be occurred.
fbdo.setBSSLBufferSize(4096 /* Rx buffer size in bytes from 512 - 16384 */, 1024 /* Tx buffer size in bytes from 512 - 16384 */);

Firebase.setDoubleDigits(5);

Firebase.begin(&config, &auth);

}

void loop() {

// Firebase.ready() should be called repeatedly to handle authentication tasks.

if (Firebase.ready() && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0))
{
    sendDataPrevMillis = millis();

    Serial_Printf("Set bool... %s\n", Firebase.RTDB.setBool(&fbdo, F("/test/bool"), count % 2 == 0) ? "ok" : fbdo.errorReason().c_str());

    count++;
}

}

mobizt commented 8 months ago

You should make your GSM module works with TinyGSMClient before using the library.

This is not a library issue.

Nikitanagar commented 8 months ago

Yeah I had done this and GSM is working properly but same error comes.

mobizt commented 8 months ago

Your GSM module is actually SIM7600 compatible AT commands.

You should read every single line of comment in example carefully to set it up.

mobizt commented 8 months ago

These two lines comments are typo.

// To allow TinyGSM library integration, the following macro should be defined in src/ESP_Mail_FS.h or
// your custom config file src/Custom_ESP_Mail_FS.h.

You should define the SIM7600 macro in this file instead. #define TINY_GSM_MODEM_SIM7600

mobizt commented 8 months ago

These pins should be changed to match your module. BAT_EN, RESET, PIN_TX, PIN_RX and PWR_PIN

Nikitanagar commented 8 months ago

In this file where i can change. Ok got it

Nikitanagar commented 8 months ago

Should i have define #define TINY_GSM_MODEM_SIM7600 only , or any other line also.

mobizt commented 8 months ago

Read it again (skip the typo lines)

// To allow TinyGSM library integration, the following macro should be defined in src/ESP_Mail_FS.h or
// your custom config file src/Custom_ESP_Mail_FS.h.
// #define TINY_GSM_MODEM_SIM7600
mobizt commented 8 months ago

These two lines comments are typo.

// To allow TinyGSM library integration, the following macro should be defined in src/ESP_Mail_FS.h or
// your custom config file src/Custom_ESP_Mail_FS.h.

You should define the SIM7600 macro in this file instead. #define TINY_GSM_MODEM_SIM7600

Nikitanagar commented 8 months ago

include "./core/Firebase_Client_Version.h"

if !FIREBASE_CLIENT_VERSION_CHECK(40408)

error "Mixed versions compilation."

endif

ifndef FirebaseFS_H

define FirebaseFS_H

define TINY_GSM_MODEM_SIM7600 // Defined here is it right

include

include "./mbfs/MB_MCU.h"

mobizt commented 8 months ago

It's ok, actually you can define it any place in that file.

Nikitanagar commented 8 months ago

Thanks a ton mobizt. It's working fine.

avinashboy commented 5 months ago

Hi, i'm also getting the same error

17:02:48.807 -> Token info: type = id token (GITKit token), status = on request
17:02:53.795 -> Token info: type = id token (GITKit token), status = error
17:02:53.795 -> Token error: code: -4, message: connection lost

here is my code:

#define TINY_GSM_MODEM_SIM7600
#define SerialAT Serial1
#include <TinyGsmClient.h>
#include <Arduino.h>
#include <Firebase_ESP_Client.h>

#include "addons/TokenHelper.h"
#include "addons/RTDBHelper.h"

// Insert Firebase project API Key
#define API_KEY ""

// Insert Authorized Username and Corresponding Password
#define USER_EMAIL ""
#define USER_PASSWORD ""

const int MODEM_RX = 27;
const int MODEM_TX = 26;
const int powerPin = 4;
const int LED_BUILTINS = 2;

// Configure TinyGSM
TinyGsm modem(SerialAT);
TinyGsmClient client(modem);

// Insert RTDB URLefine the RTDB URL
#define DATABASE_URL ""

// Define Firebase objects
FirebaseData stream;
FirebaseData fbdo;
FirebaseAuth auth;
FirebaseConfig config;

const char* myConstant = "";
const char apn[] = "";
const char gprsUser[] = "";
const char gprsPass[] = "";

#define GSM_PIN ""

// Variables to save database paths
String listenerPath = "type/" + String(myConstant) + "/method";

void streamCallback(FirebaseStream data) {
  Serial.printf("stream path, %s\nevent path, %s\ndata type, %s\nevent type, %s\n\n",
                data.streamPath().c_str(),
                data.dataPath().c_str(),
                data.dataType().c_str(),
                data.eventType().c_str());
  //printResult(data);  //see addons/RTDBHelper.h
  Serial.println();

  Serial.printf("Received stream payload size: %d (Max. %d)\n\n", data.payloadLength(), data.maxPayloadLength());
}

void streamTimeoutCallback(bool timeout) {
  if (timeout)
    Serial.println("stream timeout, resuming...\n");
  if (!stream.httpConnected())
    Serial.printf("error code: %d, reason: %s\n\n", stream.httpCode(), stream.errorReason().c_str());
}

void simConInit(){
  pinMode(powerPin, OUTPUT);
  pinMode(LED_BUILTINS, OUTPUT);
  digitalWrite(powerPin, LOW);

  SerialAT.begin(115200, SERIAL_8N1, MODEM_RX, MODEM_TX);

  // Restart takes quite some time
  // To skip it, call init() instead of restart()
  Serial.println("Initializing modem...");
  if (!modem.init()) {
    Serial.println("Failed to restart modem, delaying 10s and retrying");
    return;
  }

  // Restart takes quite some time
  // To skip it, call init() instead of restart()
  Serial.println("Initializing modem...");
  if (!modem.restart()) {
    Serial.println("Failed to restart modem, delaying 10s and retrying");
    return;
  }

  Serial.println("Waiting for network...");
  if (!modem.waitForNetwork()) {
    Serial.println(" fail");
    delay(10000);
    return;
  }
  Serial.println(" success");

  if (modem.isNetworkConnected()) {
    Serial.println("Network connected");
  }

  // GPRS connection parameters are usually set after network registration
  Serial.print(F("Connecting to "));
  Serial.print(apn);
  if (!modem.gprsConnect(apn,gprsUser,gprsPass)) {
    Serial.println(" fail");
    delay(10000);
    return;
  }
  Serial.println(" success");

  if (modem.isGprsConnected()) {
    Serial.println("LTE module connected");
  }

  modem.setNetworkMode(38);

  digitalWrite(LED_BUILTINS, HIGH);

  // Assign the api key (required)
  config.api_key = API_KEY;

  // Assign the user sign in credentials
  auth.user.email = USER_EMAIL;
  auth.user.password = USER_PASSWORD;

  // Assign the RTDB URL (required)
  config.database_url = DATABASE_URL;

  // Assign the callback function for the long running token generation task */
  config.token_status_callback = tokenStatusCallback;  //see addons/TokenHelper.h

  stream.setGSMClient(&client, &modem, GSM_PIN, apn, gprsUser, gprsPass);

  Firebase.reconnectWiFi(true);

  stream.setBSSLBufferSize(2048 /* Rx buffer size in bytes from 512 - 16384 */, 1024 /* Tx buffer size in bytes from 512 - 16384 */);

  // Assign the maximum retry of token generation
  config.max_token_generation_retry = 5;

  // Initialize the library with the Firebase authen and config
  Firebase.begin(&config, &auth);

  if (!Firebase.RTDB.beginStream(&stream, listenerPath.c_str()))
    Serial.printf("stream begin error, %s\n\n", stream.errorReason().c_str());

  // Assign a calback function to run when it detects changes on the database
  Firebase.RTDB.setStreamCallback(&stream, streamCallback, streamTimeoutCallback);

  delay(2000);
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  // SIMCON INIT
  simConInit();

}

void loop() {
  // put your main code here, to run repeatedly:
  if (Firebase.isTokenExpired()) {
    Firebase.refreshToken(&config);
    Serial.println("Refresh token");
  }

  if (!modem.isGprsConnected()) {
    Serial.println("GPRS connection lost. Reconnecting...");
    if (!modem.gprsConnect(apn)) {
      Serial.println("Failed to reconnect to cellular network.");
      // Consider delaying or restarting the ESP
      delay(10000);
      return;
    }
    Serial.println("Reconnected to cellular network.");
  }

}

I'm a newbie. Please, can anyone tell me what went wrong with this code?

mobizt commented 5 months ago

@avinashboy

https://github.com/mobizt/Firebase-ESP32/blob/9c63f30b1a72093f16395a6b83ad13ecde0b5ecb/examples/ExternalClient/GSM/Basic/Basic.ino#L15-L17

avinashboy commented 5 months ago

I have created src/FirebaseFS.h or src/CustomFirebaseFS.h, but I don't understand its purpose. Can someone explain it to me?

mobizt commented 5 months ago

@avinashboy https://github.com/mobizt/Firebase-ESP32?tab=readme-ov-file#predefined-options

avinashboy commented 5 months ago

Yeah, I got it. But I'm sorry for asking such a basic question: where can I find the file src/FirebaseFS.h?

in Arduino IDE

mobizt commented 5 months ago

@avinashboy

You are misunderstanding the basic library working concept.

The file FirebaseFS.h is the libraries configuration file which comes with the library, you don't have to create it. https://github.com/mobizt/Firebase-ESP32/blob/master/src/FirebaseFS.h

You should add this #define TINY_GSM_MODEM_SIM7600 in that file.

avinashboy commented 5 months ago

Yeah, I understood that. Where can I find the file on my computer? I'm not familiar with that part in the Arduino IDE.

mobizt commented 5 months ago

@avinashboy

Why don't you know where the library installed?

You should ask such basic question in community forum or google.