main.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. #include <stdio.h>
  2. #include "freertos/FreeRTOS.h"
  3. #include "freertos/task.h"
  4. #include "driver/gpio.h"
  5. #include "esp_rom_sys.h"
  6. #include "esp_log.h"
  7. #include "dht22.h"
  8. #include "GPS_parser.h"
  9. #include "driver/uart.h"
  10. #include <string.h>
  11. #include <sys/unistd.h>
  12. #include <sys/stat.h>
  13. #include "esp_vfs_fat.h"
  14. #include "sdmmc_cmd.h"
  15. #include "ssd1306.h"
  16. #include <driver/i2c_master.h>
  17. #include "math.h"
  18. #include "string.h"
  19. #include "esp_wifi.h"
  20. #include "esp_netif.h"
  21. #include "esp_event.h"
  22. #include "esp_http_server.h"
  23. #include "lwip/inet.h"
  24. #include "sys/stat.h"
  25. const char *DHT_TAG = "DHT22";
  26. const char *GPS_TAG = "GPS_PARSER";
  27. const char *SD_TAG = "SD_CARD";
  28. const char *OLED_TAG = "SSD1306OLED";
  29. const char *GEN_TAG = "General";
  30. #define MOUNT_POINT "/sdcard"
  31. #define PIN_NUM_MISO CONFIG_PIN_MISO
  32. #define PIN_NUM_MOSI CONFIG_PIN_MOSI
  33. #define PIN_NUM_CLK CONFIG_PIN_CLK
  34. #define PIN_NUM_CS CONFIG_PIN_CS
  35. #define PIN_NUM_SDA CONFIG_PIN_SDA
  36. #define PIN_NUM_SCL CONFIG_PIN_SCL
  37. #define PIN_TX GPIO_NUM_17
  38. #define PIN_RX GPIO_NUM_16
  39. //definicion de tiempos de pulsacion
  40. #define PULSACION_LARGA_MS 2000
  41. #define DURACION_WATCHDOG_MS 10000
  42. #define MEASUREMENT_INTERVAL_S 1
  43. #define DEG2RAD (M_PI/180.0)
  44. const int uart_buffer_size = (1024 * 2);
  45. int length = 0;
  46. uint8_t data;
  47. static gps_parser_t gps;
  48. static httpd_handle_t http_server = NULL;
  49. static esp_netif_t *ap_netif = NULL;
  50. static bool wifiActivado = false;
  51. static uint32_t wifiLastActivity = 0;
  52. extern char filename[13]; // tu archivo gpx
  53. const char *apSSID = "MiAP";
  54. const char *apPassword = "password123";
  55. struct SensorData {
  56. double latitude;
  57. double longitude;
  58. float altura;
  59. char tiempo[64];
  60. float velocidad;
  61. float temperature;
  62. float humidity;
  63. float pressure;
  64. };
  65. struct SensorData latestData;
  66. struct SensorData datosAntiguos;
  67. SemaphoreHandle_t dataMutex; // Mutex para proteger el acceso a latestData
  68. SemaphoreHandle_t buttonSemaphore; // Semáforo para la tarea del botón
  69. bool grabando = false; //inicia apagado
  70. bool finalizado = true; //indica que no hay ninguna grabacion ni iniciada ni pausada
  71. TaskHandle_t medicionesHandle = NULL; //para suspend/resume
  72. int pantallaEstado_grab = -1; //maquina de estados cuando se graba ruta
  73. int pantallaEstado_menu = -1; //maquina de estados cuando no se esta grabando ruta
  74. float distancia_total = 0.0;
  75. volatile unsigned long ignore_isr_until = 0; //para debounce
  76. char filename[13] = "/panchas.gpx";
  77. ssd1306_handle_t d = NULL;
  78. const char mount_point[] = MOUNT_POINT;
  79. void OLED_test(){
  80. i2c_master_bus_handle_t i2c_bus = i2c_bus0_init(PIN_NUM_SDA, PIN_NUM_SCL, 400000);
  81. ssd1306_config_t cfg = {
  82. .width = 128,
  83. .height = 64,
  84. .fb = NULL, // let driver allocate internally
  85. .fb_len = 0,
  86. .iface.i2c =
  87. {
  88. .port = I2C_NUM_0,
  89. .addr = 0x3C, // typical SSD1306 I2C address
  90. .rst_gpio = GPIO_NUM_NC, // no reset pin
  91. },
  92. };
  93. ESP_ERROR_CHECK(ssd1306_new_i2c(&cfg, &d));
  94. ESP_ERROR_CHECK(ssd1306_clear(d));
  95. ESP_ERROR_CHECK(ssd1306_draw_rect(d, cfg.width / 2 - 50, cfg.height / 2 - 10, 100, 20, false));
  96. ESP_ERROR_CHECK(ssd1306_display(d));
  97. ESP_ERROR_CHECK(ssd1306_draw_circle(d, cfg.width / 2, cfg.height / 2, 20, true));
  98. ESP_ERROR_CHECK(ssd1306_display(d));
  99. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 0, "Iniciando...", true, 1));
  100. ESP_ERROR_CHECK(ssd1306_display(d));
  101. vTaskDelay(pdMS_TO_TICKS(1000));
  102. }
  103. void OLED_print(const char *line1, const char *line2){
  104. ESP_ERROR_CHECK(ssd1306_clear(d));
  105. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 0, line1, true, 2));
  106. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 40, line2, true, 2));
  107. ESP_ERROR_CHECK(ssd1306_display(d));
  108. }
  109. void DHT_test (){
  110. float t;
  111. float h;
  112. esp_err_t err = dht_attach_pin();
  113. if (err != ESP_OK) {
  114. OLED_print("DHT22", "Error");
  115. ESP_LOGE(DHT_TAG, "Failed to attach DHT pin: %s", esp_err_to_name(err));
  116. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
  117. DHT_test(); //Reintentar
  118. }
  119. err = dht_read(&t, &h);
  120. if (err != ESP_OK) {
  121. OLED_print("DHT22", "Error");
  122. ESP_LOGE(DHT_TAG, "Failed to read DHT : %s", esp_err_to_name(err));
  123. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
  124. DHT_test(); //Reintentar
  125. }
  126. else OLED_print("DHT22", "Correcto");
  127. }
  128. void SD_test(){
  129. esp_vfs_fat_sdmmc_mount_config_t mount_config = {
  130. .format_if_mount_failed = false,
  131. .max_files = 5,
  132. .allocation_unit_size = 16 * 1024
  133. };
  134. sdmmc_card_t *card;
  135. sdmmc_host_t host = SDSPI_HOST_DEFAULT();
  136. host.max_freq_khz = 9000; //a mas freq no funciona, porque pipas
  137. spi_bus_config_t bus_cfg = {
  138. .mosi_io_num = PIN_NUM_MOSI,
  139. .miso_io_num = PIN_NUM_MISO,
  140. .sclk_io_num = PIN_NUM_CLK,
  141. .quadwp_io_num = -1,
  142. .quadhd_io_num = -1,
  143. .max_transfer_sz = 4092,
  144. };
  145. esp_err_t ret = spi_bus_initialize(host.slot, &bus_cfg, SDSPI_DEFAULT_DMA);
  146. if (ret != ESP_OK) {
  147. ESP_LOGE(SD_TAG, "Failed to initialize bus.");
  148. return;
  149. }
  150. sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
  151. slot_config.gpio_cs = PIN_NUM_CS;
  152. slot_config.host_id = host.slot;
  153. ESP_LOGI(SD_TAG, "Mounting filesystem");
  154. while((ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, &card)) != ESP_OK){
  155. if (ret == ESP_FAIL) {
  156. ESP_LOGE(SD_TAG, "Failed to mount filesystem. "
  157. "If you want the card to be formatted, set the CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
  158. OLED_print("Error SD", "Prueba a reinsertar");
  159. } else {
  160. ESP_LOGE(SD_TAG, "Failed to initialize the card (%s). "
  161. "Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret));
  162. OLED_print("Error SD", esp_err_to_name(ret));
  163. }
  164. vTaskDelay(pdMS_TO_TICKS(1000));
  165. }
  166. ESP_LOGI(SD_TAG, "Filesystem mounted");
  167. OLED_print("SD correcta","");
  168. // Card has been initialized, print its properties
  169. sdmmc_card_print_info(stdout, card);
  170. }
  171. void GPS_test_wait(){
  172. // Iniciar Serial2 para GPS
  173. bool fixObtained = false;
  174. uart_configurator();
  175. gps_parser_init(&gps);
  176. while (!fixObtained) {
  177. while (uart_read_bytes(UART_NUM_2, &data, 1, 0)){
  178. gps_parser_encode(&gps, data);
  179. }
  180. if (gps_location_is_valid(&gps.location) && gps_date_is_valid(&gps.date) && gps_time_is_valid(&gps.time)) {
  181. fixObtained = true;
  182. break;
  183. }
  184. vTaskDelay(pdMS_TO_TICKS(300));
  185. OLED_print("GPS", "Esperando");
  186. vTaskDelay(pdMS_TO_TICKS(300));
  187. OLED_print("GPS", "Esperando .");
  188. vTaskDelay(pdMS_TO_TICKS(300));
  189. OLED_print("GPS", "Esperando ..");
  190. vTaskDelay(pdMS_TO_TICKS(300));
  191. OLED_print("GPS", "Esperando ...");
  192. }
  193. OLED_print("GPS", "Encontrado");
  194. }
  195. float calcular_delta_dist(float lat1, float long1, float lat2, float long2){
  196. float R = 6371000.0; // Radio de la Tierra en km
  197. float delta_lat = (lat2 - lat1) * DEG2RAD;
  198. float delta_long = (long2 - long1) * DEG2RAD;
  199. lat1 = lat1 * DEG2RAD;
  200. lat2 = lat2 * DEG2RAD;
  201. float a = sin(delta_lat/2)*sin(delta_lat/2)+cos(lat1)*cos(lat2)*sin(delta_long/2)*sin(delta_long/2);
  202. float c = 2 * atan2(sqrt(a),sqrt(1-a));
  203. return R * c; //En m
  204. }
  205. void task_mediciones(void *pvParameters) {
  206. TickType_t xLastWakeTime = xTaskGetTickCount();
  207. char buffer[50];
  208. while(1) {
  209. unsigned long startMillis = pdTICKS_TO_MS(xTaskGetTickCount());
  210. // se leen los valores antes de utilizar el semaphore
  211. while (uart_read_bytes(UART_NUM_2, &data, 1, 0)){
  212. gps_parser_encode(&gps, data);
  213. }
  214. float new_latitude = gps_location_lat(&gps.location);
  215. float new_longitude = gps_location_lng(&gps.location);
  216. float new_altitude = 0.0; //gps.altitude.meters(); falta por implementar en la libreria del gps
  217. int new_fecha_len = snprintf(buffer, sizeof(buffer), "%d-%02d-%02dT%02d:%02d:%02d.%03d", gps_date_year(&gps.date), gps_date_month(&gps.date),
  218. gps_date_day(&gps.date), gps_time_hour(&gps.time), gps_time_minute(&gps.time),
  219. gps_time_second(&gps.time), gps_time_centisecond(&gps.time));
  220. if (new_fecha_len < 0) {
  221. buffer[0] = '\0';
  222. }
  223. float new_temp = 0.0;
  224. float new_hum = 0.0;
  225. dht_read(&new_temp, &new_hum);
  226. float new_press = 0.0; // Placeholder, no hay sensor de presión
  227. float distancia_ciclo = calcular_delta_dist(datosAntiguos.latitude, datosAntiguos.longitude, new_latitude, new_longitude);
  228. distancia_total += distancia_ciclo;
  229. float new_speed = distancia_ciclo / MEASUREMENT_INTERVAL_S * 3.6;
  230. if (xSemaphoreTake(dataMutex, portMAX_DELAY) == pdTRUE) {
  231. latestData.latitude = new_latitude;
  232. latestData.longitude = new_longitude;
  233. latestData.altura = new_altitude;
  234. strncpy(latestData.tiempo, buffer, sizeof(latestData.tiempo) - 1);
  235. latestData.tiempo[sizeof(latestData.tiempo) - 1] = '\0';
  236. latestData.velocidad = new_speed;
  237. latestData.temperature = new_temp;
  238. latestData.humidity = new_hum;
  239. latestData.pressure = new_press;
  240. datosAntiguos = latestData;
  241. xSemaphoreGive(dataMutex);
  242. }
  243. FILE *f = fopen(filename, "a");
  244. if (f) {
  245. //Crear la string para escribir en el archivo
  246. fprintf(f, "\t\t\t<trkpt lat=\"");
  247. fprintf(f, "%2.4f", datosAntiguos.latitude);
  248. fprintf(f, "\" lon=\"");
  249. fprintf(f, "%2.4f", datosAntiguos.longitude);
  250. fprintf(f, "\">\n");
  251. fprintf(f, "\t\t\t\t<ele>");
  252. fprintf(f, "%f", datosAntiguos.altura);
  253. fprintf(f, "</ele>\n");
  254. fprintf(f, "\t\t\t\t<time>");
  255. fprintf(f, "%s", datosAntiguos.tiempo);
  256. fprintf(f, "</time>\n");
  257. fprintf(f, "\t\t\t\t<speed>");
  258. fprintf(f, "%f", datosAntiguos.velocidad);
  259. fprintf(f, "</speed>\n");
  260. fprintf(f, "\t\t\t\t<extensions>\n");
  261. fprintf(f, "\t\t\t\t\t<gpxtpx:TrackPointExtension>\n");
  262. fprintf(f, "\t\t\t\t\t\t<gpxtpx:atemp>");
  263. fprintf(f, "%f", datosAntiguos.temperature);
  264. fprintf(f, "</gpxtpx:atemp>\n");
  265. fprintf(f, "\t\t\t\t\t</gpxtpx:TrackPointExtension>\n");
  266. fprintf(f, "\t\t\t\t\t<custom:humidity>");
  267. fprintf(f, "%f", datosAntiguos.humidity);
  268. fprintf(f, "</custom:humidity>\n");
  269. fprintf(f, "\t\t\t\t\t<custom:pressure>");
  270. fprintf(f, "%f", datosAntiguos.pressure);
  271. fprintf(f, "</custom:pressure>\n");
  272. fprintf(f, "\t\t\t\t</extensions>\n");
  273. fprintf(f, "\t\t\t</trkpt>\n");
  274. fclose(f);
  275. }
  276. unsigned long elapsedMillis = pdTICKS_TO_MS(xTaskGetTickCount()) - startMillis;
  277. ESP_LOGI(GEN_TAG, "Elapsed millis: %d.", elapsedMillis);
  278. vTaskDelayUntil(&xLastWakeTime, pdMS_TO_TICKS(MEASUREMENT_INTERVAL_S*1000)); // Espera x*1000 milisegundos
  279. }
  280. }
  281. void crear_archivo(){
  282. int num = 1;
  283. sprintf(filename, MOUNT_POINT"/data%03d.gpx", num);
  284. FILE *f = fopen(filename, "r");
  285. while (f != NULL) {
  286. num++;
  287. sprintf(filename, MOUNT_POINT"/data%03d.gpx", num);
  288. FILE *f = fopen(filename, "r");
  289. }
  290. FILE *f = fopen(filename, "w");
  291. char buffer[50];
  292. if (f) {
  293. fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  294. "<gpx creator=\"ESP32 GPS LOGGER\" version=\"1.1\"\n"
  295. "\txmlns=\"http://www.topografix.com/GPX/1/1\"\n"
  296. "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  297. "\txmlns:gpxtpx=\"http://www.garmin.com/xmlschemas/TrackPointExtension/v2\"\n"
  298. "\txmlns:gpxdata=\"http://www.cluetrust.com/XML/GPXDATA/1/0\"\n"
  299. "\txsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n"
  300. "\t<metadata>\n"
  301. "\t\t<name>Ruta grabada con ESP32 GPS Logger</name>\n"
  302. "\t\t<time>\n");
  303. int new_fecha_len = snprintf(buffer, sizeof(buffer), "%d-%02d-%02dT%02d:%02d:%02d.%03d", gps_date_year(&gps.date), gps_date_month(&gps.date),
  304. gps_date_day(&gps.date), gps_time_hour(&gps.time), gps_time_minute(&gps.time),
  305. gps_time_second(&gps.time), gps_time_centisecond(&gps.time));
  306. if (new_fecha_len < 0) {
  307. buffer[0] = '\0';
  308. }
  309. fprintf(f, "%s", buffer);
  310. fprintf(f, "</time>\n\t</metadata>\n"
  311. "\t<trk>\n"
  312. "\t\t<name>Rutita</name>\n"
  313. "\t\t<type>hiking</type>\n"
  314. "\t\t<trkseg>\n");
  315. fclose(f);
  316. } else {
  317. OLED_print("Error","creando archivo");
  318. vTaskDelay(pdMS_TO_TICKS(2000));
  319. crear_archivo();
  320. }
  321. }
  322. void cerrar_archivo() {
  323. FILE *f = fopen(filename, "w");
  324. if (f){
  325. fprintf(f, "\t\t</trkseg>\n\t</trk>\n</gpx>");
  326. fclose(f);
  327. }
  328. //int num = 1;
  329. //sprintf(filename, "/data%03d.gpx", num);
  330. //while (SD.exists(filename)) {
  331. // num++;
  332. // sprintf(filename, "/data%03d.gpx", num);
  333. //}
  334. }
  335. void activarWiFi(void)
  336. {
  337. OLED_print("WiFi", "Activando...");
  338. ESP_ERROR_CHECK(wifi_ap_init());
  339. char ip_str[16] = {0};
  340. get_ap_ip(ip_str, sizeof(ip_str));
  341. OLED_print("WiFi Activo", ip_str);
  342. vTaskDelay(pdMS_TO_TICKS(2000));
  343. ESP_ERROR_CHECK(iniciar_servidor_http());
  344. wifiActivado = true;
  345. wifiLastActivity = xTaskGetTickCount();
  346. }
  347. void desactivarWiFi(void)
  348. {
  349. if (http_server) {
  350. httpd_stop(http_server);
  351. http_server = NULL;
  352. }
  353. ESP_ERROR_CHECK(esp_wifi_stop());
  354. ESP_ERROR_CHECK(esp_wifi_deinit());
  355. if (ap_netif) {
  356. esp_netif_destroy(ap_netif);
  357. ap_netif = NULL;
  358. }
  359. wifiActivado = false;
  360. OLED_print("WiFi", "Apagado");
  361. }
  362. void app_main(void)
  363. {
  364. // Initialize DHT22 sensor
  365. /*
  366. float temperature;
  367. float humidity;
  368. esp_err_t err = dht_attach_pin();
  369. if (err != ESP_OK) {
  370. ESP_LOGE(DHT_TAG, "Failed to attach DHT pin: %s", esp_err_to_name(err));
  371. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
  372. return;
  373. }
  374. vTaskDelay(pdMS_TO_TICKS(2000)); // Wait for 2 seconds before starting the main loop
  375. while (1) {
  376. if (dht_read(&temperature, &humidity) == ESP_OK) {
  377. ESP_LOGI(DHT_TAG, "Temperature: %.1f°C, Humidity: %.1f%%", temperature, humidity);
  378. } else {
  379. ESP_LOGE(DHT_TAG, "Failed to read from DHT22 sensor");
  380. }
  381. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before the next reading
  382. }
  383. */
  384. // Initialize GPS parser
  385. /*
  386. uart_configurator();
  387. double latitude, longitude;
  388. gps_parser_init(&gps);
  389. while(1){
  390. while (uart_read_bytes(UART_NUM_2, &data, 1, 0)){
  391. gps_parser_encode(&gps, data);
  392. }
  393. if (gps_location_is_valid(&gps.location)) {
  394. double lat = gps_location_lat(&gps.location);
  395. double lng = gps_location_lng(&gps.location);
  396. ESP_LOGI(GPS_TAG, "Lat: %.8f, Lng: %.8f", lat, lng);
  397. }
  398. if (gps_date_is_valid(&gps.date) && gps_time_is_valid(&gps.time)) {
  399. ESP_LOGI(GPS_TAG, "Fecha: %02u/%02u/%04u Hora: %02u:%02u:%02u\n",
  400. gps_date_day(&gps.date),
  401. gps_date_month(&gps.date),
  402. gps_date_year(&gps.date),
  403. gps_time_hour(&gps.time),
  404. gps_time_minute(&gps.time),
  405. gps_time_second(&gps.time));
  406. }
  407. vTaskDelay(pdMS_TO_TICKS(2000)); // Wait for 1 second before the next reading
  408. }
  409. */
  410. // Initialize SD card
  411. /*
  412. esp_vfs_fat_sdmmc_mount_config_t mount_config = {
  413. .format_if_mount_failed = false,
  414. .max_files = 5,
  415. .allocation_unit_size = 16 * 1024
  416. };
  417. sdmmc_card_t *card;
  418. const char mount_point[] = MOUNT_POINT;
  419. sdmmc_host_t host = SDSPI_HOST_DEFAULT();
  420. host.max_freq_khz = 9000; //a mas freq no funciona, porque pipas
  421. spi_bus_config_t bus_cfg = {
  422. .mosi_io_num = PIN_NUM_MOSI,
  423. .miso_io_num = PIN_NUM_MISO,
  424. .sclk_io_num = PIN_NUM_CLK,
  425. .quadwp_io_num = -1,
  426. .quadhd_io_num = -1,
  427. .max_transfer_sz = 4092,
  428. };
  429. esp_err_t ret = spi_bus_initialize(host.slot, &bus_cfg, SDSPI_DEFAULT_DMA);
  430. if (ret != ESP_OK) {
  431. ESP_LOGE(SD_TAG, "Failed to initialize bus.");
  432. return;
  433. }
  434. gpio_set_pull_mode(PIN_NUM_MISO, GPIO_PULLUP_ONLY);
  435. sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
  436. slot_config.gpio_cs = PIN_NUM_CS;
  437. slot_config.host_id = host.slot;
  438. ESP_LOGI(SD_TAG, "Mounting filesystem");
  439. ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, &card);
  440. if (ret != ESP_OK) {
  441. if (ret == ESP_FAIL) {
  442. ESP_LOGE(SD_TAG, "Failed to mount filesystem. "
  443. "If you want the card to be formatted, set the CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
  444. } else {
  445. ESP_LOGE(SD_TAG, "Failed to initialize the card (%s). "
  446. "Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret));
  447. }
  448. return;
  449. }
  450. ESP_LOGI(SD_TAG, "Filesystem mounted");
  451. // Card has been initialized, print its properties
  452. sdmmc_card_print_info(stdout, card);
  453. const char *file_foo = MOUNT_POINT"/foo.txt";
  454. // Check if destination file exists before renaming
  455. struct stat st;
  456. if (stat(file_foo, &st) == 0) {
  457. // Delete it if it exists
  458. unlink(file_foo);
  459. }
  460. const char *file_nihao = MOUNT_POINT"/nihao.txt";
  461. // All done, unmount partition and disable SPI peripheral
  462. esp_vfs_fat_sdcard_unmount(mount_point, card);
  463. ESP_LOGI(SD_TAG, "Card unmounted");
  464. //deinitialize the bus after all devices are removed
  465. spi_bus_free(host.slot);
  466. */
  467. // Initialize display
  468. /*
  469. i2c_master_bus_handle_t i2c_bus =
  470. i2c_bus0_init(GPIO_NUM_21, GPIO_NUM_22, 400000);
  471. ssd1306_config_t cfg = {
  472. .width = 128,
  473. .height = 64,
  474. .fb = NULL, // let driver allocate internally
  475. .fb_len = 0,
  476. .iface.i2c =
  477. {
  478. .port = I2C_NUM_0,
  479. .addr = 0x3C, // typical SSD1306 I2C address
  480. .rst_gpio = GPIO_NUM_NC, // no reset pin
  481. },
  482. };
  483. ssd1306_handle_t d = NULL;
  484. ESP_ERROR_CHECK(ssd1306_new_i2c(&cfg, &d));
  485. // ----- Clear screen -----
  486. ESP_ERROR_CHECK(ssd1306_clear(d));
  487. // ----- Draw pixels in corners of screen -----
  488. ESP_ERROR_CHECK(ssd1306_draw_pixel(d, 0, 0, true));
  489. ESP_ERROR_CHECK(ssd1306_draw_pixel(d, cfg.width - 1, 0, true));
  490. ESP_ERROR_CHECK(ssd1306_draw_pixel(d, 0, cfg.height - 1, true));
  491. ESP_ERROR_CHECK(ssd1306_draw_pixel(d, cfg.width - 1, cfg.height - 1, true));
  492. // ----- Draw rectangles -----
  493. ESP_ERROR_CHECK(ssd1306_draw_rect(d, 2, 2, 40, 20, false));
  494. ESP_ERROR_CHECK(ssd1306_draw_rect(d, 2, 24, 32, 16, true));
  495. // ----- Draw circles -----
  496. ESP_ERROR_CHECK(ssd1306_draw_circle(d, 32, 52, 8, true));
  497. ESP_ERROR_CHECK(ssd1306_draw_circle(d, 100, 52, 4, false));
  498. // ----- Draw lines -----
  499. ESP_ERROR_CHECK(ssd1306_draw_line(d, 2, 2, 40, 20, true));
  500. ESP_ERROR_CHECK(ssd1306_draw_line(d, 32, 52, 100, 52, true));
  501. // ----- Draw text -----
  502. ESP_ERROR_CHECK(ssd1306_draw_text(d, 48, 2, "OK!", true));
  503. ESP_ERROR_CHECK(
  504. ssd1306_draw_text_scaled(d, 48, 10, "Hello\nWorld!", true, 2));
  505. ESP_ERROR_CHECK(ssd1306_display(d));
  506. ESP_LOGI(OLED_TAG, "Display updated successfully.");
  507. */
  508. }
  509. void uart_configurator() {
  510. // Configure UART parameters
  511. uart_config_t uart_config = {
  512. .baud_rate = 115200,
  513. .data_bits = UART_DATA_8_BITS,
  514. .parity = UART_PARITY_DISABLE,
  515. .stop_bits = UART_STOP_BITS_1,
  516. .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
  517. };
  518. QueueHandle_t uart_queue;
  519. // Install UART driver using an event queue here
  520. ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, uart_buffer_size, uart_buffer_size, 10, &uart_queue, 0));
  521. ESP_ERROR_CHECK(uart_param_config(UART_NUM_2, &uart_config));
  522. ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, PIN_TX, PIN_RX, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
  523. }
  524. static esp_err_t s_example_write_file(const char *path, char *data)
  525. {
  526. ESP_LOGI(SD_TAG, "Opening file %s", path);
  527. FILE *f = fopen(path, "w");
  528. if (f == NULL) {
  529. ESP_LOGE(SD_TAG, "Failed to open file for writing");
  530. return ESP_FAIL;
  531. }
  532. fprintf(f, data);
  533. fclose(f);
  534. ESP_LOGI(SD_TAG, "File written");
  535. return ESP_OK;
  536. }
  537. // Init i2c
  538. static i2c_master_bus_handle_t i2c_bus0_init(gpio_num_t sda, gpio_num_t scl, uint32_t hz) {
  539. i2c_master_bus_config_t bus_cfg = {
  540. .i2c_port = I2C_NUM_0,
  541. .sda_io_num = sda,
  542. .scl_io_num = scl,
  543. .clk_source = I2C_CLK_SRC_DEFAULT,
  544. .glitch_ignore_cnt = 0,
  545. .flags.enable_internal_pullup = true,
  546. };
  547. i2c_master_bus_handle_t bus = NULL;
  548. ESP_ERROR_CHECK(i2c_new_master_bus(&bus_cfg, &bus));
  549. // NOTE: per-device speed is set when adding the device (in driver bind).
  550. return bus;
  551. }
  552. static esp_err_t wifi_ap_init(void)
  553. {
  554. esp_err_t err;
  555. ESP_ERROR_CHECK(esp_netif_init());
  556. ESP_ERROR_CHECK(esp_event_loop_create_default());
  557. ap_netif = esp_netif_create_default_wifi_ap();
  558. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  559. ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  560. ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
  561. wifi_config_t wifi_config = {
  562. .ap = {
  563. .ssid = "",
  564. .ssid_len = 0,
  565. .channel = 1,
  566. .password = "",
  567. .max_connection = 4,
  568. .authmode = WIFI_AUTH_WPA_WPA2_PSK,
  569. },
  570. };
  571. strncpy((char *)wifi_config.ap.ssid, apSSID, sizeof(wifi_config.ap.ssid) - 1);
  572. strncpy((char *)wifi_config.ap.password, apPassword, sizeof(wifi_config.ap.password) - 1);
  573. if (strlen(apPassword) == 0) {
  574. wifi_config.ap.authmode = WIFI_AUTH_OPEN;
  575. }
  576. ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config));
  577. ESP_ERROR_CHECK(esp_wifi_start());
  578. return ESP_OK;
  579. }
  580. static esp_err_t get_ap_ip(char *out_ip, size_t len)
  581. {
  582. esp_netif_ip_info_t ip_info;
  583. if (ap_netif == NULL) {
  584. return ESP_ERR_INVALID_STATE;
  585. }
  586. ESP_ERROR_CHECK(esp_netif_get_ip_info(ap_netif, &ip_info));
  587. inet_ntoa_r(ip_info.ip, out_ip, len);
  588. return ESP_OK;
  589. }
  590. static esp_err_t root_get_handler(httpd_req_t *req)
  591. {
  592. wifiLastActivity = xTaskGetTickCount();
  593. char ip_str[16] = {0};
  594. get_ap_ip(ip_str, sizeof(ip_str));
  595. const char *nombreArchivo = (filename[0] == '/') ? filename + 1 : filename;
  596. char html[1024];
  597. snprintf(html, sizeof(html),
  598. "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>ESP32 GPS Logger</title>"
  599. "<style>body{font-family:Arial;text-align:center;margin:50px;}h1{color:#333;} "
  600. "a.button{background:#4CAF50;color:white;padding:20px 40px;text-decoration:none;"
  601. "font-size:24px;border-radius:12px;display:inline-block;margin:20px;}</style></head>"
  602. "<body><h1>GPS Logger</h1><p>Archivo listo para descargar:</p>"
  603. "<a href='/download' class='button' download='%s'>Descargar %s</a>"
  604. "<hr><p>IP: %s</p><p>Se apagará en 5 min sin uso.</p></body></html>",
  605. nombreArchivo, nombreArchivo, ip_str);
  606. httpd_resp_set_type(req, "text/html");
  607. return httpd_resp_send(req, html, HTTPD_RESP_USE_STRLEN);
  608. }
  609. static esp_err_t download_get_handler(httpd_req_t *req)
  610. {
  611. wifiLastActivity = xTaskGetTickCount();
  612. struct stat st;
  613. if (stat(filename, &st) != 0) {
  614. httpd_resp_send_404(req);
  615. return ESP_FAIL;
  616. }
  617. FILE *file = fopen(filename, "r");
  618. if (!file) {
  619. httpd_resp_send_404(req);
  620. return ESP_FAIL;
  621. }
  622. const char *nombreArchivo = (filename[0] == '/') ? filename + 1 : filename;
  623. char disposition[128];
  624. snprintf(disposition, sizeof(disposition),
  625. "attachment; filename=\"%s\"", nombreArchivo);
  626. httpd_resp_set_type(req, "application/gpx+xml");
  627. httpd_resp_set_hdr(req, "Content-Disposition", disposition);
  628. httpd_resp_send_file(req, file, st.st_size);
  629. fclose(file);
  630. return ESP_OK;
  631. }
  632. static const httpd_uri_t root_uri = {
  633. .uri = "/",
  634. .method = HTTP_GET,
  635. .handler = root_get_handler,
  636. .user_ctx = NULL
  637. };
  638. static const httpd_uri_t download_uri = {
  639. .uri = "/download",
  640. .method = HTTP_GET,
  641. .handler = download_get_handler,
  642. .user_ctx = NULL
  643. };
  644. static esp_err_t iniciar_servidor_http(void)
  645. {
  646. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  647. if (httpd_start(&http_server, &config) != ESP_OK) {
  648. return ESP_FAIL;
  649. }
  650. httpd_register_uri_handler(http_server, &root_uri);
  651. httpd_register_uri_handler(http_server, &download_uri);
  652. return ESP_OK;
  653. }