TCP connection failed, code: -1 #182
-
Excuse me, I want to ask you my trouble. When I'm trying your example code to using realtime database it works. But, if I'm using my code using sim800l it doesnt works with this error: this my all code #define TINY_GSM_MODEM_SIM800
#define SerialMon Serial
#define SerialAT Serial2
#define SerialGPS Serial1
#define TINY_GSM_DEBUG SerialMon
#define GSM_PIN ""
// set GSM PIN, if any
//#define GSM_PIN ""
// Your GPRS credentials, if any
const char apn[] = "internet";
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)
// ESP32 and SIM800l pins
#define MODEM_TX 4
#define MODEM_RX 2
// ESP32 and GPS pins
#define GPS_TX_PIN 17
#define GPS_RX_PIN 16
// Include TinyGsmClient.h first and followed by FirebaseClient.h
#include <Arduino.h>
#include <TinyGsmClient.h>
#include <FirebaseClient.h> // https://github.com/mobizt/ESP_SSLClient
#include <TinyGPS++.h>
// The API key can be obtained from Firebase console > Project Overview > Project settings.
#define API_KEY ""
// User Email and password that already registerd or added in your project.
#define USER_EMAIL ""
#define USER_PASSWORD ""
#define DATABASE_URL ""
TinyGsm modem(SerialAT);
TinyGsmClient gsm_client1(modem, 0);
TinyGPSPlus gps;
ESP_SSLClient ssl_client1;
GSMNetwork gsm_network(&modem, GSM_PIN, apn, gprsUser, gprsPass);
UserAuth user_auth(API_KEY, USER_EMAIL, USER_PASSWORD);
FirebaseApp app;
using AsyncClient = AsyncClientClass;
AsyncClient aClient1(ssl_client1, getNetwork(gsm_network));
void asyncCB(AsyncResult &aResult);
void printResult(AsyncResult &aResult);
RealtimeDatabase Database;
unsigned long ms = 0;
void setup() {
SerialMon.begin(115200);
delay(1000);
SerialMon.println("Wait ...");
SerialGPS.begin(9600, SERIAL_8N1, GPS_TX_PIN, GPS_RX_PIN);
SerialAT.begin(115200, SERIAL_8N1, MODEM_TX, MODEM_RX);
delay(3000);
SerialMon.println("Initializing modem ...");
modem.restart();
String modemInfo = modem.getModemInfo();
SerialMon.print("Modem Info: ");
SerialMon.println(modemInfo);
// Unlock your sim card with a PIN if needed
if (GSM_PIN && modem.getSimStatus() != 3) {
modem.simUnlock(GSM_PIN);
}
SerialMon.print("Waiting for network...");
if (!modem.waitForNetwork()) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" success");
if (modem.isNetworkConnected()) {
DBG("Network connected");
}
String ccid = modem.getSimCCID();
DBG("CCID:", ccid);
delay(100);
String imei = modem.getIMEI();
DBG("IMEI:", imei);
delay(100);
String imsi = modem.getIMSI();
DBG("IMSI:", imsi);
delay(100);
String cop = modem.getOperator();
DBG("Operator:", cop);
delay(100);
SerialMon.print("Connecting to APN: ");
SerialMon.print(apn);
if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
SerialMon.println(" fail");
ESP.restart();
}
SerialMon.println(" OK");
delay(100);
if (modem.isGprsConnected()) {
SerialMon.println("GPRS connected");
}
delay(100);
IPAddress local = modem.localIP();
DBG("Local IP:", local);
delay(100);
int csq = modem.getSignalQuality();
DBG("Signal quality:", csq);
delay(1000);
Firebase.printf("Firebase Client v%s\n", FIREBASE_CLIENT_VERSION);
ssl_client1.setInsecure();
ssl_client1.setDebugLevel(1);
ssl_client1.setBufferSizes(2048 /* rx */, 1024 /* tx */);
ssl_client1.setClient(&gsm_client1);
Serial.println("Initializing app...");
initializeApp(aClient1, app, getAuth(user_auth), asyncCB, "authTask");
app.getApp<RealtimeDatabase>(Database);
Database.url(DATABASE_URL);
// Database.setSSEFilters("get,put,patch,keep-alive,cancel,auth_revoked");
// Database.get(aClient2, "/value/", asyncCB, true /* SSE mode */, "streamTask");
}
void loop() {
app.loop();
Database.loop();
if (millis() - ms > 20000 && app.ready()) {
char lat_str[12];
char lng_str[12];
Serial.println("Getting data: ");
float lat = 0, lng = 0;
for (int i = 2; i; i--) {
while (SerialGPS.available() > 0) {
gps.encode(SerialGPS.read());
}
delay(1000);
}
if (gps.location.isValid()) {
lat = gps.location.lat();
lng = gps.location.lng();
dtostrf(lat, 8, 6, lat_str);
dtostrf(lng, 8, 6, lng_str);
Serial.print("Latitude = ");
Serial.println(lat_str);
Serial.print("Longitude= ");
Serial.println(lng_str);
} else {
Serial.println(F("Invalid"));
}
ms = millis();
// JsonWriter writer;
// object_t json, obj1, obj2;
// writer.create(obj1, "lat", 123);
// writer.create(obj2, "lng", 123);
// writer.join(json, 2, obj1, obj2);
// String name = Database.push<object_t>(aClient1, "/neo_6m/", json);
object_t json;
JsonWriter writer;
writer.create(json, "test/data", 123); // -> {"test":{"data":123}}
// Or set the seialized JSON string to object_t as object_t("{\"test\":{\"data\":123}}")
Serial.print("Push JSON... ");
String name = Database.push<object_t>(aClient1, "/test/json", json);
if (aClient1.lastError().code() == 0)
Firebase.printf("ok, name: %s\n", name.c_str());
else
printError(aClient1.lastError().code(), aClient1.lastError().message());
}
}
void asyncCB(AsyncResult &aResult) {
// WARNING!
// Do not put your codes inside the callback and printResult.
printResult(aResult);
}
void printResult(AsyncResult &aResult) {
if (aResult.isEvent()) {
Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.appEvent().message().c_str(), aResult.appEvent().code());
}
if (aResult.isDebug()) {
Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());
}
if (aResult.isError()) {
Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());
}
if (aResult.available()) {
RealtimeDatabaseResult &RTDB = aResult.to<RealtimeDatabaseResult>();
if (RTDB.isStream()) {
Serial.println("----------------------------");
Firebase.printf("task: %s\n", aResult.uid().c_str());
Firebase.printf("event: %s\n", RTDB.event().c_str());
Firebase.printf("path: %s\n", RTDB.dataPath().c_str());
Firebase.printf("data: %s\n", RTDB.to<const char *>());
Firebase.printf("type: %d\n", RTDB.type());
// The stream event from RealtimeDatabaseResult can be converted to the values as following.
bool v1 = RTDB.to<bool>();
int v2 = RTDB.to<int>();
float v3 = RTDB.to<float>();
double v4 = RTDB.to<double>();
String v5 = RTDB.to<String>();
} else {
Serial.println("----------------------------");
Firebase.printf("task: %s, payload: %s\n", aResult.uid().c_str(), aResult.c_str());
}
Firebase.printf("Free Heap: %d\n", ESP.getFreeHeap());
}
}
void printError(int code, const String &msg)
{
Firebase.printf("Error, msg: %s, code: %d\n", msg.c_str(), code);
} I need your help :"( |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 16 replies
-
You are using async library as this Firebase library that it runs repeatedly in loop, your blocking code that you place in the loop will block the Firebase library to run correctly because of data sending or receiving timed out. You should move all your other code out of the loop and run it in separate FreeRTOS task instead. If you still want to run your blocking code in loop, you should use the Firebase library in sync mode. |
Beta Was this translation helpful? Give feedback.
-
I always convince this in the documentation and all examples. Important Do not underestimate the important the async task handler location and usage. The non-async third-party library and user blocking code, |
Beta Was this translation helpful? Give feedback.
-
In that code, I'm implementing from example sync push to realtime database and change from loop to setup, but i still got same error |
Beta Was this translation helpful? Give feedback.
-
Due to many editions. This is my test code. Please change the Serial port to match your hardware. #include <Arduino.h>
#define DATABASE_URL "......"
#define DATABASE_SECRET "......."
#define API_KEY "......."
#define USER_EMAIL "......."
#define USER_PASSWORD "......."
#define TINY_GSM_MODEM_SIM7600
#define SerialMon Serial
#define SerialAT Serial1
#define TINY_GSM_DEBUG SerialMon
#define TINY_GSM_USE_GPRS true
#define TINY_GSM_USE_WIFI false
#define GSM_PIN ""
const char apn[] = "YourAPN";
const char gprsUser[] = "";
const char gprsPass[] = "";
#define uS_TO_S_FACTOR 1000000ULL
#define TIME_TO_SLEEP 600
#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 <TinyGsmClient.h>
#include <FirebaseClient.h>
TinyGsm modem(SerialAT);
TinyGsmClient gsm_client1(modem, 0);
ESP_SSLClient ssl_client1;
GSMNetwork gsm_network(&modem, GSM_PIN, apn, gprsUser, gprsPass);
UserAuth user_auth(API_KEY, USER_EMAIL, USER_PASSWORD);
FirebaseApp app;
using AsyncClient = AsyncClientClass;
AsyncClient aClient1(ssl_client1, getNetwork(gsm_network));
void authHandler();
void asyncCB(AsyncResult &aResult);
void printResult(AsyncResult &aResult);
void printError(int code, const String &msg);
RealtimeDatabase Database;
unsigned long ms = 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);
DBG("Initializing modem...");
if (!modem.init())
{
DBG("Failed to restart modem, delaying 10s and retrying");
return;
}
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);
Firebase.printf("Firebase Client v%s\n", FIREBASE_CLIENT_VERSION);
ssl_client1.setInsecure();
ssl_client1.setDebugLevel(1);
ssl_client1.setBufferSizes(2048 /* rx */, 1024 /* tx */);
ssl_client1.setClient(&gsm_client1);
initializeApp(aClient1, app, getAuth(user_auth), asyncCB, "authTask");
app.getApp<RealtimeDatabase>(Database);
Database.url(DATABASE_URL);
}
void loop()
{
app.loop();
Database.loop();
if (millis() - ms > 20000 && app.ready())
{
ms = millis();
object_t json;
JsonWriter writer;
writer.create(json, "test/data", 123);
// For your clarification.
// This is the sync function which runs immediately and waits the returning result from the function.
// On other hand, async function (run later in the queue) requires the AsyncResult or AsyncResultCallback (asyncCB) function to get the result later and will not return anything from function.
// The auth task handler that runs in the loop will handle the async tasks (adding by async functions) store in the AsyncClient queue.
// The initializeApp runs in the setup above is async function because it takes asyncCB as parameter to get the result later.
Serial.print("Push JSON... ");
String name = Database.push<object_t>(aClient1, "/test/json", json);
if (aClient1.lastError().code() == 0)
Firebase.printf("ok, name: %s\n", name.c_str());
else
printError(aClient1.lastError().code(), aClient1.lastError().message());
}
}
void asyncCB(AsyncResult &aResult)
{
printResult(aResult);
}
void printResult(AsyncResult &aResult)
{
if (aResult.isEvent())
{
Firebase.printf("Event task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.appEvent().message().c_str(), aResult.appEvent().code());
}
if (aResult.isDebug())
{
Firebase.printf("Debug task: %s, msg: %s\n", aResult.uid().c_str(), aResult.debug().c_str());
}
if (aResult.isError())
{
Firebase.printf("Error task: %s, msg: %s, code: %d\n", aResult.uid().c_str(), aResult.error().message().c_str(), aResult.error().code());
}
}
void printError(int code, const String &msg)
{
Firebase.printf("Error, msg: %s, code: %d\n", msg.c_str(), code);
}
|
Beta Was this translation helpful? Give feedback.
-
However, you should spend the time to read library documentation thoroughly. All examples testing also requires for adaptation. |
Beta Was this translation helpful? Give feedback.
Your database url is wrong.
Why? The slash at the end.
You should be careful in programming.