Files
board-mate/esp32-thread/border-router/main/gps.c
2025-12-25 21:28:59 +01:00

111 lines
3.2 KiB
C

#include "gps.h"
#include "driver/uart.h"
#include "esp_log.h"
#include "esp_http_client.h"
#include <string.h>
#include <stdlib.h>
#define GPS_UART_NUM UART_NUM_1
#define GPS_TX_PIN 4
#define GPS_RX_PIN 5
#define BUF_SIZE 1024
static uint8_t gps_buffer[BUF_SIZE];
void init_gps() {
const uart_config_t uart_config = {
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE
};
uart_param_config(GPS_UART_NUM, &uart_config);
uart_set_pin(GPS_UART_NUM, GPS_TX_PIN, GPS_RX_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
uart_driver_install(GPS_UART_NUM, BUF_SIZE, 0, 0, NULL, 0);
}
// Convertit NMEA "ddmm.mmmm" + N/S/E/W en degrés décimaux
double nmea_to_decimal(const char* nmea_coord, const char direction) {
double raw = atof(nmea_coord);
int degrees = (int)(raw / 100);
double minutes = raw - (degrees * 100);
double decimal = degrees + minutes / 60.0;
if (direction == 'S' || direction == 'W') decimal = -decimal;
return decimal;
}
char* gps_to_json(char* gps_data) {
static char json[128];
double latitude = 0.0;
double longitude = 0.0;
if (gps_data && strncmp(gps_data, "$GPGGA,", 7) == 0) {
char* fields[15];
int i = 0;
char gps_copy[BUF_SIZE];
strncpy(gps_copy, gps_data, BUF_SIZE - 1);
gps_copy[BUF_SIZE - 1] = '\0';
char* token = strtok(gps_copy, ",");
while (token && i < 15) {
fields[i++] = token;
token = strtok(NULL, ",");
}
if (i >= 6 && fields[2][0] != '\0' && fields[4][0] != '\0') {
latitude = nmea_to_decimal(fields[2], fields[3][0]);
longitude = nmea_to_decimal(fields[4], fields[5][0]);
}
}
// Créer le JSON avec des valeurs valides même si GPS pas fixé
snprintf(json, sizeof(json), "{\"data\":{\"latitude\":%.6f,\"longitude\":%.6f}}",
latitude, longitude);
return json;
}
char* read_gps() {
int len = uart_read_bytes(GPS_UART_NUM, gps_buffer, BUF_SIZE - 1, 100 / portTICK_PERIOD_MS);
if (len > 0) {
gps_buffer[len] = '\0';
return (char*)gps_buffer;
}
return NULL;
}
void send_gps_data(const char* server_url, const char* json)
{
if (!json) return;
ESP_LOGI(TAG, "Sending JSON: %s", json);
esp_http_client_config_t config = { .url = server_url };
esp_http_client_handle_t client = esp_http_client_init(&config);
esp_http_client_set_method(client, HTTP_METHOD_POST);
esp_http_client_set_post_field(client, json, strlen(json));
esp_http_client_set_header(client, "Content-Type", "application/json");
esp_http_client_perform(client);
esp_http_client_cleanup(client);
}
void send_position_task(void *pvParameters)
{
const char* position_endpoint = "http://192.168.15.117:5000/devices/notify-position";
while (1) {
char* json;
char* raw_data = read_gps();
if (raw_data) {
char* json = gps_to_json(raw_data);
send_gps_data(position_endpoint, json);
} else {
ESP_LOGI(TAG, "NO GPS DATA");
}
vTaskDelay(25000 / portTICK_PERIOD_MS);
}
}