Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sending GPS data to Firebase #200

Open
J7a7m2m8y5 opened this issue Dec 19, 2024 · 14 comments
Open

Sending GPS data to Firebase #200

J7a7m2m8y5 opened this issue Dec 19, 2024 · 14 comments

Comments

@J7a7m2m8y5
Copy link

J7a7m2m8y5 commented Dec 19, 2024

Hi` guys, I'm new to programming the A7672E board. I want to send my GPS to firebase database. But I keep getting bad request error. I modified the Https client example code from the repository. I just replaced the URL, the resource path and the port. I would be glad if someone can help me with a code. Thank you

`#define TINY_GSM_MODEM_A7670

#include "utilities.h"
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h>

// Set serial for debug console
#define SerialMon Serial

#define TINY_GSM_USE_GPRS true
#define TINY_GSM_USE_WIFI false

// Set GSM PIN
#define GSM_PIN ""

// Your GPRS credentials
const char apn[] = "web.gprs.mtnnigeria.net";
const char gprsUser[] = "web";
const char gprsPass[] = "web";

// Firebase details
const char firebaseHost[] = "firebaseio.com";
const char firebaseAuth[] = "auth-token"; // Firebase Database Secret
const int firebasePort = 443; //

#ifdef DUMP_AT_COMMANDS
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif

TinyGsmClient client(modem);
HttpClient http(client, firebaseHost, firebasePort);

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

// Turn on DC boost to power on the modem

#ifdef BOARD_POWERON_PIN
pinMode(BOARD_POWERON_PIN, OUTPUT);
digitalWrite(BOARD_POWERON_PIN, HIGH);
#endif

// Set modem reset
pinMode(MODEM_RESET_PIN, OUTPUT);
digitalWrite(MODEM_RESET_PIN, !MODEM_RESET_LEVEL);
// Turn on modem
pinMode(BOARD_PWRKEY_PIN, OUTPUT);
digitalWrite(BOARD_PWRKEY_PIN, LOW);
delay(100);
digitalWrite(BOARD_PWRKEY_PIN, HIGH);
delay(1000);
digitalWrite(BOARD_PWRKEY_PIN, LOW);

// Set modem baud and initialize communication
SerialAT.begin(115200, SERIAL_8N1, MODEM_RX_PIN, MODEM_TX_PIN);
Serial.println("Initializing modem...");
if (!modem.init()) {
    Serial.println("Failed to initialize modem!");
    return;
}

// Connect to GPRS
Serial.println("Connecting to GPRS...");
if (!modem.gprsConnect(apn, gprsUser, gprsPass)) {
    Serial.println("Failed to connect to GPRS!");
    return;
}
Serial.println("GPRS connected.");

}

void loop() {
// Simulate GPS data (replace with actual GPS code if available)
String latitude = "6.5244"; // Example latitude
String longitude = "3.3792"; // Example longitude

// Construct JSON payload
String payload = "{";
payload += "\"latitude\": \"" + latitude + "\",";
payload += "\"longitude\": \"" + longitude + "\"";
payload += "}";

// Prepare Firebase endpoint
String firebaseEndpoint = "/gps-data.json?auth=" + String(firebaseAuth);

// Send HTTP POST request to Firebase
Serial.println("Sending data to Firebase...");
http.beginRequest();
http.post(firebaseEndpoint);
http.sendHeader("Content-Type", "application/json");
http.sendHeader("Content-Length", payload.length());
http.beginBody();
http.print(payload);
http.endRequest();

// Get response
int statusCode = http.responseStatusCode();
String response = http.responseBody();

Serial.print("Response Code: ");
Serial.println(statusCode);
Serial.print("Response: ");
Serial.println(response);

// Wait before sending next update
delay(30000); // 30 seconds delay between updates

}
`

@lewisxhe
Copy link
Contributor

A7672E ? ?
Which board do you use?

@J7a7m2m8y5
Copy link
Author

A7672E ? ? Which board do you use?

A7672E FASE

@lewisxhe
Copy link
Contributor

I haven't seen this version. Is it a LilyGo board?
Send AT+SIMCOMATI to check the version

@J7a7m2m8y5
Copy link
Author

-1088269232-1250086587

@J7a7m2m8y5
Copy link
Author

My bad😞 I meant T-A7670

@lewisxhe
Copy link
Contributor

The example you are using does not support https requests. Please use the https request example test. Please make sure that the request URL is accessible before testing.

@J7a7m2m8y5
Copy link
Author

The example you are using does not support https requests. Please use the https request example test. Please make sure that the request URL is accessible before testing.

Please can you help me with a sample code of sending and requesting data from firebase?

@lewisxhe
Copy link
Contributor

What is Firebase? I haven't heard of it. Please send me a link to see if it can help you.

@J7a7m2m8y5
Copy link
Author

What is Firebase? I haven't heard of it. Please send me a link to see if it can help you.

Google firebase database. There's a Firebase URL and Firebase authentication secret code and also a path. The SSL port for firebase is 443

@lewisxhe
Copy link
Contributor

Google? Well, Google is blocked in my country by the firewall, I can't connect via 4G, so I can't help you.

@J7a7m2m8y5
Copy link
Author

Google? Well, Google is blocked in my country by the firewall, I can't connect via 4G, so I can't help you.

Okay, thank you so much. I really appreciate it

@J7a7m2m8y5
Copy link
Author

J7a7m2m8y5 commented Dec 20, 2024

This code seems to work fine through WiFi Client. But I've been getting errors trying to use TinyGSM Library with the Esp32 Firebase library.

` #define TINY_GSM_MODEM_A7670
#include "utilities.h"

#define TINY_GSM_RX_BUFFER 1024  // Set RX buffer to 1Kb
#define SerialAT Serial1

// See all AT commands, if wanted
#define DUMP_AT_COMMANDS



#include <TinyGsmClient.h>
#include <TinyGPSPlus.h>

#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#endif
#include <Firebase_ESP_Client.h>

//Provide the token generation process info.
#include "addons/TokenHelper.h"
//Provide the RTDB payload printing info and other helper functions.
#include "addons/RTDBHelper.h"

// Your GPRS credentials, if any
const char apn[] = "web.gprs.mtnnigeria.net";
const char gprsUser[] = "web";
const char gprsPass[] = "web";

#ifdef DUMP_AT_COMMANDS
#include <StreamDebugger.h>
StreamDebugger debugger(SerialAT, SerialMon);
TinyGsm modem(debugger);
#else
TinyGsm modem(SerialAT);
#endif

// The TinyGPSPlus object
TinyGPSPlus gps;


// Insert your network credentials
#define WIFI_SSID "xxxxxxxx"
#define WIFI_PASSWORD "xxxxxxxx"

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

// Insert RTDB URLefine the RTDB URL */
#define DATABASE_URL "https://xxxxxxxxxxxxxxxxxxxxxxxxxxx.com/"

//Define Firebase Data object
FirebaseData fbdo;

FirebaseAuth auth;
FirebaseConfig config;

unsigned long sendDataPrevMillis = 0;
int count = 0;
bool signupOK = false;

void displayInfo();

void setup() {
  Serial.begin(115200);
  // Turn on DC boost to power on the modem
  pinMode(BOARD_POWERON_PIN, OUTPUT);
  digitalWrite(BOARD_POWERON_PIN, LOW);

  // Set modem reset pin ,reset modem
  pinMode(MODEM_RESET_PIN, OUTPUT);
  digitalWrite(MODEM_RESET_PIN, !MODEM_RESET_LEVEL);
  delay(100);
  digitalWrite(MODEM_RESET_PIN, MODEM_RESET_LEVEL);
  delay(2600);
  digitalWrite(MODEM_RESET_PIN, !MODEM_RESET_LEVEL);

  // Turn on modem
  pinMode(BOARD_PWRKEY_PIN, OUTPUT);
  digitalWrite(BOARD_PWRKEY_PIN, LOW);
  delay(100);
  digitalWrite(BOARD_PWRKEY_PIN, HIGH);
  delay(1000);
  digitalWrite(BOARD_PWRKEY_PIN, LOW);

  // Set modem baud
  SerialAT.begin(115200, SERIAL_8N1, MODEM_RX_PIN, MODEM_TX_PIN);

  Serial.println("Start modem...");
  delay(3000);

  /*
    *   During testing, it was found that there may be a power outage.
        Add a loop detection here. When the GPS timeout does not start,
        resend the AT to check if the modem is online
    * */
  Serial.print("Modem starting...");
  int retry = 0;
  while (!modem.testAT(1000)) {
    Serial.println(".");
    if (retry++ > 10) {
      digitalWrite(BOARD_PWRKEY_PIN, LOW);
      delay(100);
      digitalWrite(BOARD_PWRKEY_PIN, HIGH);
      delay(1000);  //Ton = 1000ms ,Min = 500ms, Max 2000ms
      digitalWrite(BOARD_PWRKEY_PIN, LOW);
      retry = 0;
    }
  }
  Serial.println();

  delay(200);

  Serial.println("GPS Ready!");

  modem.enableGPS(MODEM_GPS_ENABLE_GPIO);

  modem.setGPSBaud(115200);

  modem.setGPSMode(3);  //GPS + BD

  modem.configNMEASentence(1, 1, 1, 1, 1, 1);

  modem.setGPSOutputRate(1);

  modem.enableNMEA();

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();


  // Serial.println(F("Sats HDOP  Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum"));
  // Serial.println(F("           (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
  // Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

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

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

  /* Sign up */
  if (Firebase.signUp(&config, &auth, "", "")) {
    Serial.println("ok");
    signupOK = true;
  } else {
    Serial.printf("%s\n", config.signer.signupError.message.c_str());
  }

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

  Firebase.begin(&config, &auth);
  Firebase.reconnectWiFi(true);
}

void loop() {
  // Simple show loaction
  // displayInfo()

  // Show full information


 
  if (Firebase.ready() && signupOK && (millis() - sendDataPrevMillis > 15000 || sendDataPrevMillis == 0)) {
    sendDataPrevMillis = millis();
    // Write an Int number on the database path test/int
    Firebase.RTDB.setInt(&fbdo, "HIS001/Altitude", gps.altitude.meters());
    Firebase.RTDB.setInt(&fbdo, "HIS001/Satellite", gps.satellites.value());

    // Write an Float number on the database path test/float
    Firebase.RTDB.setFloat(&fbdo, "HIS001/Latitude", gps.location.lat());
    Firebase.RTDB.setFloat(&fbdo, "HIS001/Longitude", gps.location.lng());
    Firebase.RTDB.setFloat(&fbdo, "HIS001/HDOP (m)", gps.hdop.hdop());
    Firebase.RTDB.setFloat(&fbdo, "HIS001/Course (deg)", gps.course.deg());
    Firebase.RTDB.setFloat(&fbdo, "HIS001/Speed", gps.speed.kmph());


    // Write an Float number on the database path test/float
    Firebase.RTDB.setString(&fbdo, "HIS001/Date", String(gps.date.day()) + "/" + String(gps.date.month()) + "/" + String(gps.date.year()));
    Firebase.RTDB.setString(&fbdo, "HIS001/Time", String(gps.time.hour()) + ":" + String(gps.time.minute()) + ":" + String(gps.time.second()));
    //smartDelay(1000);
  }
  smartDelay(1000);
}




// This custom version of delay() ensures that the gps object
// is being "fed".
static void smartDelay(unsigned long ms) {
  int ch = 0;
  unsigned long start = millis();
  do {
    while (SerialAT.available()) {
      ch = SerialAT.read();
      // Serial.write(ch);
      gps.encode(ch);
    }
  } while (millis() - start < ms);
}

`

@lewisxhe
Copy link
Contributor

You should use the secure client instead of the unencrypted client
https://github.com/Xinyuan-LilyGO/LilyGO-T-A76XX/tree/main/examples/SecureClient

@J7a7m2m8y5
Copy link
Author

You should use the secure client instead of the unencrypted client https://github.com/Xinyuan-LilyGO/LilyGO-T-A76XX/tree/main/examples/SecureClient

This works 😁😁😁 Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants