A9G GSM/GPRS Module with Traccar

Radar2 years ago

I am making a tracking device with A9G GSM GPRS Module and ESP32. Which protocol and port should I use to communicate with TRACCAR? Also, if anyone has ESP32 and A9G tracking device Arduino ide code, can they share it?

Anton Tananaev2 years ago

You can use any of the supported protocols.

Radar2 years ago

I do not know how to write the code for protocols other than the osmand protocol. I wonder if there is a friend with an example esp32 code can help?

Jean Andrade2 months ago
#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_RX_BUFFER 1024 // Tamanho do buffer de recepção
#define SerialMon Serial
#define SerialGPRS Serial1
#define Serial_GPS Serial2
#define TINY_GSM_TEST_BATTERY true
#define BUFFER_SIZE 100 // Define o tamanho do buffer

#include <TinyGsmClient.h>
#include <TinyGPS++.h>
#include "utilities.h"  // confg de inicializaçaão

static const uint32_t BAUD_RATE = 9600;
static const uint32_t GSM_RATE = 115200;
static const uint32_t GPS_RATE = 230400;

const unsigned long RESET_INTERVAL = 6UL * 60UL * 60UL * 1000UL; // 6 horas
const unsigned long SEND_INTERVAL = 1500;
const unsigned long RECONNECT_INTERVAL = 160000;
const unsigned long BUFFER_SEND_INTERVAL = 10000; // Novo intervalo para tentar enviar o buffer

static unsigned long lastResetTime = 0;
static unsigned long lastSendTime = 0;
static unsigned long lastReconnectAttempt = 0;
static unsigned long lastBufferSendAttempt = 0; // Novo tempo para enviar o buffer

void sendBuffer();
bool wasConnected = false;

#define APN  "claro.com.br"
#define USER "claro"
#define PASS "claro"

const char deviceId[] = "739155";
const char server[] = "104.23";
const int port = 5055;

TinyGsm modem(SerialGPRS);
TinyGsmClient client(modem);
TinyGPSPlus gps;

void connectGPRS() {
  const int maxAttempts = 5;
  int attempt = 0;

  while (attempt < maxAttempts) {
    if (modem.gprsConnect(APN, USER, PASS)) {
      SerialMon.println("\nConectado!");
      IPAddress local = modem.localIP();
      SerialMon.println(local);
      wasConnected = true;
      return;
    } else {
      attempt++;
      SerialMon.print("Falha ao conectar. Tentativa ");
      SerialMon.print(attempt);
      SerialMon.print(" de ");
      SerialMon.println(maxAttempts);
      delay(5000);
    }
  }
  SerialMon.println("Falha ao conectar após várias tentativas. Reiniciando modem...");
  modem.restart();
}

void resetModulo() {
  unsigned long currentTime = millis();
  if (currentTime - lastResetTime >= RESET_INTERVAL) {
    SerialMon.println("Reiniciando ESP32...");
    lastResetTime = currentTime;
    ESP.restart();
  }
}

void ledStatus() {
  pinMode(LED_GPIO, OUTPUT);
  digitalWrite(LED_GPIO, LED_ON);
  delay(500);
  digitalWrite(LED_GPIO, LED_OFF);
}

float ajustaVelocidade(float speed) {
  return (speed <= 3.00) ? 0.00 : speed;
}

struct LocationData {
  unsigned long timestamp;
  double latitude;
  double longitude;
  int satellites;
  float speed;
  float course;
  float altitude;
  float battery;
  int rssi;
};

LocationData buffer[BUFFER_SIZE];
int bufferIndex = 0;

void storeInBuffer(LocationData data) {
  if (bufferIndex < BUFFER_SIZE) {
    buffer[bufferIndex++] = data;
    SerialMon.println("Dados armazenados no buffer.");
  } else {
    SerialMon.println("Buffer cheio. Tentando envio forçado...");
    sendBuffer();
  }
}

void sendBuffer() {
  if (millis() - lastBufferSendAttempt < BUFFER_SEND_INTERVAL) return;
  lastBufferSendAttempt = millis();

  for (int i = 0; i < bufferIndex; i++) {
    String url = "/?id=" + String(deviceId) +
                 "×tamp=" + String(buffer[i].timestamp) +
                 "&lat=" + String(buffer[i].latitude, 6) +
                 "&lon=" + String(buffer[i].longitude, 6) +
                 "&sat=" + String(buffer[i].satellites) +
                 "&speed=" + String(buffer[i].speed, 1) +
                 "&bearing=" + String(buffer[i].course, 1) +
                 "&altitude=" + String(buffer[i].altitude, 1) +
                 "&battery=" + String(buffer[i].battery) +
                 "&rssi=" + String(buffer[i].rssi) +
                 "&ignition=1";

    if (client.connect(server, port)) {
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                   "Host: " + server + "\r\n" +
                   "Connection: close\r\n\r\n");
      client.stop();
      SerialMon.println("Dados enviados do buffer com sucesso.");
    } else {
      SerialMon.println("Falha ao conectar ao servidor. Tentando novamente.");
      return;
    }
  }
  bufferIndex = 0;
}

void sendLocation() {
  if (millis() - lastSendTime > SEND_INTERVAL) {
    lastSendTime = millis();
    if (gps.location.isValid()) {
      unsigned long timestamp = gps.time.value();
      double latitude = gps.location.lat();
      double longitude = gps.location.lng();
      int satellites = gps.satellites.value();
      float speed = ajustaVelocidade(gps.speed.kmph());
      float course = gps.course.deg();
      float altitude = gps.altitude.meters();
      float battery = modem.getBattVoltage() / 1000.0F;
      int rssi = modem.getSignalQuality();

      LocationData data = {timestamp, latitude, longitude, satellites, speed, course, altitude, battery, rssi};

      if (modem.isGprsConnected()) {
        if (client.connect(server, port)) {
          String url = "/?id=" + String(deviceId) +
                       "×tamp=" + String(timestamp) +
                       "&lat=" + String(latitude, 6) +
                       "&lon=" + String(longitude, 6) +
                       "&sat=" + String(satellites) +
                       "&speed=" + String(speed, 1) +
                       "&bearing=" + String(course, 1) +
                       "&altitude=" + String(altitude, 1) +
                       "&battery=" + String(battery) +
                       "&rssi=" + String(rssi) +
                       "&ignition=1";

          client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                       "Host: " + server + "\r\n" +
                       "Connection: close\r\n\r\n");
          client.stop();
          SerialMon.println("Dados enviados com sucesso.");
          ledStatus();
          sendBuffer();
        } else {
          SerialMon.println("Falha ao conectar ao servidor. Armazenando dados no buffer.");
          storeInBuffer(data);
        }
      } else {
        SerialMon.println("Sem conexão GPRS. Armazenando dados no buffer.");
        storeInBuffer(data);
      }
    }
  }
}

void setup() {
  SerialMon.begin(BAUD_RATE);
  setupModem();
  delay(10);

  Serial_GPS.begin(GPS_RATE, SERIAL_8N1, GPS_RX, GPS_TX);
  SerialMon.println("Inicializando GPS...");
  delay(2000);

  SerialGPRS.begin(GSM_RATE, SERIAL_8N1, MODEM_RX, MODEM_TX);
  SerialMon.println("Inicializando GSM...");
  delay(2000);

  SerialMon.println("Restarting modem...");
  modem.restart();
  delay(1000);

  String ccid = modem.getSimCCID();
  Serial.println("CCID: " + ccid);

  String imei = modem.getIMEI();
  Serial.println("IMEI: " + imei);

  String cop = modem.getOperator();
  Serial.println("Operator: " + cop);
  
  IPAddress local = modem.localIP();
  Serial.println("Local IP: " + String(local));

  int csq = modem.getSignalQuality();
  Serial.println("Signal quality: " + String(csq));
 
  SerialMon.print("Conectando a Internet... ");
  connectGPRS();


}

void loop() {
  while (Serial_GPS.available() > 0) {
    gps.encode(Serial_GPS.read());
    sendLocation();
  }

  if (!modem.isGprsConnected()) {
    if (!wasConnected || millis() - lastReconnectAttempt > RECONNECT_INTERVAL) {
      lastReconnectAttempt = millis();
      SerialMon.println("Reconectando ao GPRS...");
      connectGPRS();
      wasConnected = modem.isGprsConnected();
    }
  } else {
    wasConnected = true;
  }

  resetModulo();
}