main.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. #include "driver/gpio.h"
  26. #include "esp_attr.h"
  27. #include "esp_pm.h"
  28. const char *DHT_TAG = "DHT22";
  29. const char *GPS_TAG = "GPS_PARSER";
  30. const char *SD_TAG = "SD_CARD";
  31. const char *OLED_TAG = "SSD1306OLED";
  32. const char *GEN_TAG = "General";
  33. #define MOUNT_POINT "/sdcard"
  34. #define PIN_NUM_MISO CONFIG_PIN_MISO
  35. #define PIN_NUM_MOSI CONFIG_PIN_MOSI
  36. #define PIN_NUM_CLK CONFIG_PIN_CLK
  37. #define PIN_NUM_CS CONFIG_PIN_CS
  38. #define PIN_NUM_SDA CONFIG_PIN_SDA
  39. #define PIN_NUM_SCL CONFIG_PIN_SCL
  40. #define PIN_TX GPIO_NUM_17
  41. #define PIN_RX GPIO_NUM_16
  42. #define PIN_BUTTON CONFIG_PIN_BUTTON
  43. //definicion de tiempos de pulsacion
  44. #define PULSACION_LARGA_MS 2000
  45. #define DURACION_WATCHDOG_MS 10000
  46. #define WIFI_TIMEOUT_MS 3000000
  47. #define MEASUREMENT_INTERVAL_S 1
  48. #define DEG2RAD (M_PI/180.0)
  49. const int uart_buffer_size = (1024 * 2);
  50. int length = 0;
  51. uint8_t data;
  52. static gps_parser_t gps;
  53. static httpd_handle_t http_server = NULL;
  54. static esp_netif_t *ap_netif = NULL;
  55. static bool wifiActivado = false;
  56. static uint32_t wifiLastActivity = 0;
  57. extern char filename[64]; // tu archivo gpx
  58. const char *apSSID = "MiAP";
  59. const char *apPassword = "password123";
  60. struct SensorData {
  61. double latitude;
  62. double longitude;
  63. float altura;
  64. char tiempo[64];
  65. float velocidad;
  66. float temperature;
  67. float humidity;
  68. float pressure;
  69. };
  70. struct SensorData latestData;
  71. struct SensorData datosAntiguos;
  72. SemaphoreHandle_t dataMutex; // Mutex para proteger el acceso a latestData
  73. SemaphoreHandle_t buttonSemaphore; // Semáforo para la tarea del botón
  74. bool grabando = false; //inicia apagado
  75. bool finalizado = true; //indica que no hay ninguna grabacion ni iniciada ni pausada
  76. TaskHandle_t medicionesHandle = NULL; //para suspend/resume
  77. int pantallaEstado_grab = -1; //maquina de estados cuando se graba ruta
  78. int pantallaEstado_menu = -1; //maquina de estados cuando no se esta grabando ruta
  79. float distancia_total = 0.0;
  80. volatile unsigned long ignore_isr_until = 0; //para debounce
  81. char filename[64] = "/panchas.gpx";
  82. ssd1306_handle_t d = NULL;
  83. i2c_master_dev_handle_t i2c_dev_handle = NULL;
  84. const char mount_point[] = MOUNT_POINT;
  85. // Configuración del GPIO del botón
  86. gpio_config_t btn_cfg = {
  87. .pin_bit_mask = (1ULL << PIN_BUTTON),
  88. .mode = GPIO_MODE_INPUT,
  89. .pull_up_en = GPIO_PULLUP_ENABLE,
  90. .pull_down_en = GPIO_PULLDOWN_DISABLE,
  91. .intr_type = GPIO_INTR_NEGEDGE, // FALLING = flanco de bajada
  92. };
  93. void uart_configurator() {
  94. // Configure UART parameters
  95. uart_config_t uart_config = {
  96. .baud_rate = 115200,
  97. .data_bits = UART_DATA_8_BITS,
  98. .parity = UART_PARITY_DISABLE,
  99. .stop_bits = UART_STOP_BITS_1,
  100. .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
  101. };
  102. QueueHandle_t uart_queue;
  103. // Install UART driver using an event queue here
  104. ESP_ERROR_CHECK(uart_driver_install(UART_NUM_2, uart_buffer_size, uart_buffer_size, 10, &uart_queue, 0));
  105. ESP_ERROR_CHECK(uart_param_config(UART_NUM_2, &uart_config));
  106. ESP_ERROR_CHECK(uart_set_pin(UART_NUM_2, PIN_TX, PIN_RX, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
  107. }
  108. // Init i2c
  109. static i2c_master_bus_handle_t i2c_bus0_init(gpio_num_t sda, gpio_num_t scl, uint32_t hz) {
  110. i2c_master_bus_config_t bus_cfg = {
  111. .i2c_port = I2C_NUM_0,
  112. .sda_io_num = sda,
  113. .scl_io_num = scl,
  114. .clk_source = I2C_CLK_SRC_DEFAULT,
  115. .glitch_ignore_cnt = 0,
  116. .flags.enable_internal_pullup = true,
  117. };
  118. i2c_master_bus_handle_t bus = NULL;
  119. ESP_ERROR_CHECK(i2c_new_master_bus(&bus_cfg, &bus));
  120. // NOTE: per-device speed is set when adding the device (in driver bind).
  121. return bus;
  122. }
  123. static esp_err_t wifi_ap_init(void)
  124. {
  125. ESP_ERROR_CHECK(esp_netif_init());
  126. ESP_ERROR_CHECK(esp_event_loop_create_default());
  127. ap_netif = esp_netif_create_default_wifi_ap();
  128. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  129. ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  130. ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
  131. wifi_config_t wifi_config = {
  132. .ap = {
  133. .ssid = "",
  134. .ssid_len = 0,
  135. .channel = 1,
  136. .password = "",
  137. .max_connection = 4,
  138. .authmode = WIFI_AUTH_WPA_WPA2_PSK,
  139. },
  140. };
  141. strncpy((char *)wifi_config.ap.ssid, apSSID, sizeof(wifi_config.ap.ssid) - 1);
  142. strncpy((char *)wifi_config.ap.password, apPassword, sizeof(wifi_config.ap.password) - 1);
  143. if (strlen(apPassword) == 0) {
  144. wifi_config.ap.authmode = WIFI_AUTH_OPEN;
  145. }
  146. ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &wifi_config));
  147. ESP_ERROR_CHECK(esp_wifi_start());
  148. return ESP_OK;
  149. }
  150. static esp_err_t get_ap_ip(char *out_ip, size_t len)
  151. {
  152. esp_netif_ip_info_t ip_info;
  153. if (ap_netif == NULL) {
  154. return ESP_ERR_INVALID_STATE;
  155. }
  156. ESP_ERROR_CHECK(esp_netif_get_ip_info(ap_netif, &ip_info));
  157. inet_ntoa_r(ip_info.ip, out_ip, len);
  158. return ESP_OK;
  159. }
  160. static esp_err_t root_get_handler(httpd_req_t *req)
  161. {
  162. wifiLastActivity = xTaskGetTickCount();
  163. char ip_str[16] = {0};
  164. get_ap_ip(ip_str, sizeof(ip_str));
  165. const char *nombreArchivo = (filename[0] == '/') ? filename + 1 : filename;
  166. char html[1024];
  167. snprintf(html, sizeof(html),
  168. "<!DOCTYPE html><html><head><meta charset='UTF-8'><title>ESP32 GPS Logger</title>"
  169. "<style>body{font-family:Arial;text-align:center;margin:50px;}h1{color:#333;} "
  170. "a.button{background:#4CAF50;color:white;padding:20px 40px;text-decoration:none;"
  171. "font-size:24px;border-radius:12px;display:inline-block;margin:20px;}</style></head>"
  172. "<body><h1>GPS Logger</h1><p>Archivo listo para descargar:</p>"
  173. "<a href='/download' class='button' download='%s'>Descargar %s</a>"
  174. "<hr><p>IP: %s</p><p>Se apagará en 5 min sin uso.</p></body></html>",
  175. nombreArchivo, nombreArchivo, ip_str);
  176. httpd_resp_set_type(req, "text/html");
  177. return httpd_resp_send(req, html, HTTPD_RESP_USE_STRLEN);
  178. }
  179. static esp_err_t stream_file_response(httpd_req_t *req, FILE *file)
  180. {
  181. char buf[1024];
  182. size_t read_len;
  183. esp_err_t ret;
  184. while ((read_len = fread(buf, 1, sizeof(buf), file)) > 0) {
  185. ret = httpd_resp_send_chunk(req, buf, read_len);
  186. if (ret != ESP_OK) {
  187. fclose(file);
  188. return ret;
  189. }
  190. }
  191. fclose(file);
  192. return httpd_resp_send_chunk(req, NULL, 0);
  193. }
  194. static esp_err_t download_get_handler(httpd_req_t *req)
  195. {
  196. wifiLastActivity = xTaskGetTickCount();
  197. struct stat st;
  198. if (stat(filename, &st) != 0) {
  199. httpd_resp_send_404(req);
  200. return ESP_FAIL;
  201. }
  202. FILE *file = fopen(filename, "r");
  203. if (!file) {
  204. httpd_resp_send_404(req);
  205. return ESP_FAIL;
  206. }
  207. const char *nombreArchivo = (filename[0] == '/') ? filename + 1 : filename;
  208. char disposition[128];
  209. snprintf(disposition, sizeof(disposition),
  210. "attachment; filename=\"%s\"", nombreArchivo);
  211. httpd_resp_set_type(req, "application/gpx+xml");
  212. httpd_resp_set_hdr(req, "Content-Disposition", disposition);
  213. return stream_file_response(req, file);
  214. }
  215. static const httpd_uri_t root_uri = {
  216. .uri = "/",
  217. .method = HTTP_GET,
  218. .handler = root_get_handler,
  219. .user_ctx = NULL
  220. };
  221. static const httpd_uri_t download_uri = {
  222. .uri = "/download",
  223. .method = HTTP_GET,
  224. .handler = download_get_handler,
  225. .user_ctx = NULL
  226. };
  227. static esp_err_t iniciar_servidor_http(void)
  228. {
  229. httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  230. if (httpd_start(&http_server, &config) != ESP_OK) {
  231. return ESP_FAIL;
  232. }
  233. httpd_register_uri_handler(http_server, &root_uri);
  234. httpd_register_uri_handler(http_server, &download_uri);
  235. return ESP_OK;
  236. }
  237. void OLED_test(){
  238. i2c_master_bus_handle_t i2c_bus = i2c_bus0_init(PIN_NUM_SDA, PIN_NUM_SCL, 400000);
  239. ssd1306_config_t cfg = {
  240. .width = 128,
  241. .height = 64,
  242. .fb = NULL, // let driver allocate internally
  243. .fb_len = 0,
  244. .iface.i2c =
  245. {
  246. .port = I2C_NUM_0,
  247. .addr = 0x3C, // typical SSD1306 I2C address
  248. .rst_gpio = GPIO_NUM_NC, // no reset pin
  249. },
  250. };
  251. i2c_device_config_t dev_cfg = {
  252. .dev_addr_length = I2C_ADDR_BIT_LEN_7,
  253. .device_address = 0x3C,
  254. .scl_speed_hz = 400000,
  255. };
  256. i2c_master_bus_add_device(i2c_bus, &dev_cfg, &i2c_dev_handle);
  257. ESP_ERROR_CHECK(ssd1306_new_i2c(&cfg, &d));
  258. ESP_ERROR_CHECK(ssd1306_clear(d));
  259. ESP_ERROR_CHECK(ssd1306_draw_rect(d, cfg.width / 2 - 50, cfg.height / 2 - 10, 100, 20, false));
  260. ESP_ERROR_CHECK(ssd1306_display(d));
  261. ESP_ERROR_CHECK(ssd1306_draw_circle(d, cfg.width / 2, cfg.height / 2, 20, true));
  262. ESP_ERROR_CHECK(ssd1306_display(d));
  263. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 0, "Iniciando...", true, 1));
  264. ESP_ERROR_CHECK(ssd1306_display(d));
  265. vTaskDelay(pdMS_TO_TICKS(1000));
  266. }
  267. void OLED_print(const char *line1, const char *line2){
  268. ESP_ERROR_CHECK(ssd1306_clear(d));
  269. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 0, line1, true, 2));
  270. ESP_ERROR_CHECK(ssd1306_draw_text_scaled(d, 0, 40, line2, true, 2));
  271. ESP_ERROR_CHECK(ssd1306_display(d));
  272. }
  273. void DHT_test (){
  274. float t;
  275. float h;
  276. esp_err_t err = dht_attach_pin();
  277. if (err != ESP_OK) {
  278. OLED_print("DHT22", "Error");
  279. ESP_LOGE(DHT_TAG, "Failed to attach DHT pin: %s", esp_err_to_name(err));
  280. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
  281. DHT_test(); //Reintentar
  282. }
  283. err = dht_read(&t, &h);
  284. if (err != ESP_OK) {
  285. OLED_print("DHT22", "Error");
  286. ESP_LOGE(DHT_TAG, "Failed to read DHT : %s", esp_err_to_name(err));
  287. vTaskDelay(pdMS_TO_TICKS(5000)); // Wait for 5 seconds before retrying
  288. DHT_test(); //Reintentar
  289. }
  290. else OLED_print("DHT22", "Correcto");
  291. }
  292. void SD_test(){
  293. esp_vfs_fat_sdmmc_mount_config_t mount_config = {
  294. .format_if_mount_failed = false,
  295. .max_files = 5,
  296. .allocation_unit_size = 16 * 1024
  297. };
  298. sdmmc_card_t *card;
  299. sdmmc_host_t host = SDSPI_HOST_DEFAULT();
  300. host.max_freq_khz = 9000; //a mas freq no funciona, porque pipas
  301. spi_bus_config_t bus_cfg = {
  302. .mosi_io_num = PIN_NUM_MOSI,
  303. .miso_io_num = PIN_NUM_MISO,
  304. .sclk_io_num = PIN_NUM_CLK,
  305. .quadwp_io_num = -1,
  306. .quadhd_io_num = -1,
  307. .max_transfer_sz = 4092,
  308. };
  309. esp_err_t ret = spi_bus_initialize(host.slot, &bus_cfg, SDSPI_DEFAULT_DMA);
  310. if (ret != ESP_OK) {
  311. ESP_LOGE(SD_TAG, "Failed to initialize bus.");
  312. return;
  313. }
  314. sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
  315. slot_config.gpio_cs = PIN_NUM_CS;
  316. slot_config.host_id = host.slot;
  317. ESP_LOGI(SD_TAG, "Mounting filesystem");
  318. while((ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, &card)) != ESP_OK){
  319. if (ret == ESP_FAIL) {
  320. ESP_LOGE(SD_TAG, "Failed to mount filesystem. "
  321. "If you want the card to be formatted, set the CONFIG_EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
  322. OLED_print("Error SD", "Prueba a reinsertar");
  323. } else {
  324. ESP_LOGE(SD_TAG, "Failed to initialize the card (%s). "
  325. "Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret));
  326. OLED_print("Error SD", esp_err_to_name(ret));
  327. }
  328. vTaskDelay(pdMS_TO_TICKS(1000));
  329. }
  330. ESP_LOGI(SD_TAG, "Filesystem mounted");
  331. OLED_print("SD correcta","");
  332. // Card has been initialized, print its properties
  333. sdmmc_card_print_info(stdout, card);
  334. }
  335. void GPS_test_wait(){
  336. // Iniciar Serial2 para GPS
  337. bool fixObtained = false;
  338. uart_configurator();
  339. gps_parser_init(&gps);
  340. while (!fixObtained) {
  341. while (uart_read_bytes(UART_NUM_2, &data, 1, 0)){
  342. gps_parser_encode(&gps, data);
  343. }
  344. if (gps_location_is_valid(&gps.location) && gps_date_is_valid(&gps.date) && gps_time_is_valid(&gps.time)) {
  345. fixObtained = true;
  346. break;
  347. }
  348. vTaskDelay(pdMS_TO_TICKS(300));
  349. OLED_print("GPS", "Esperando");
  350. vTaskDelay(pdMS_TO_TICKS(300));
  351. OLED_print("GPS", "Esperando .");
  352. vTaskDelay(pdMS_TO_TICKS(300));
  353. OLED_print("GPS", "Esperando ..");
  354. vTaskDelay(pdMS_TO_TICKS(300));
  355. OLED_print("GPS", "Esperando ...");
  356. }
  357. OLED_print("GPS", "Encontrado");
  358. }
  359. float calcular_delta_dist(float lat1, float long1, float lat2, float long2){
  360. float R = 6371000.0; // Radio de la Tierra en km
  361. float delta_lat = (lat2 - lat1) * DEG2RAD;
  362. float delta_long = (long2 - long1) * DEG2RAD;
  363. lat1 = lat1 * DEG2RAD;
  364. lat2 = lat2 * DEG2RAD;
  365. float a = sin(delta_lat/2)*sin(delta_lat/2)+cos(lat1)*cos(lat2)*sin(delta_long/2)*sin(delta_long/2);
  366. float c = 2 * atan2(sqrt(a),sqrt(1-a));
  367. return R * c; //En m
  368. }
  369. void task_mediciones(void *pvParameters) {
  370. TickType_t xLastWakeTime = xTaskGetTickCount();
  371. char buffer[50];
  372. while(1) {
  373. unsigned long startMillis = pdTICKS_TO_MS(xTaskGetTickCount());
  374. // se leen los valores antes de utilizar el semaphore
  375. while (uart_read_bytes(UART_NUM_2, &data, 1, 0)){
  376. gps_parser_encode(&gps, data);
  377. }
  378. float new_latitude = gps_location_lat(&gps.location);
  379. float new_longitude = gps_location_lng(&gps.location);
  380. float new_altitude = 0.0; //gps.altitude.meters(); falta por implementar en la libreria del gps
  381. 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),
  382. gps_date_day(&gps.date), gps_time_hour(&gps.time), gps_time_minute(&gps.time),
  383. gps_time_second(&gps.time), gps_time_centisecond(&gps.time));
  384. if (new_fecha_len < 0) {
  385. buffer[0] = '\0';
  386. }
  387. float new_temp = 0.0;
  388. float new_hum = 0.0;
  389. dht_read(&new_temp, &new_hum);
  390. float new_press = 0.0; // Placeholder, no hay sensor de presión
  391. float distancia_ciclo = calcular_delta_dist(datosAntiguos.latitude, datosAntiguos.longitude, new_latitude, new_longitude);
  392. distancia_total += distancia_ciclo;
  393. float new_speed = distancia_ciclo / MEASUREMENT_INTERVAL_S * 3.6;
  394. if (xSemaphoreTake(dataMutex, portMAX_DELAY) == pdTRUE) {
  395. latestData.latitude = new_latitude;
  396. latestData.longitude = new_longitude;
  397. latestData.altura = new_altitude;
  398. strncpy(latestData.tiempo, buffer, sizeof(latestData.tiempo) - 1);
  399. latestData.tiempo[sizeof(latestData.tiempo) - 1] = '\0';
  400. latestData.velocidad = new_speed;
  401. latestData.temperature = new_temp;
  402. latestData.humidity = new_hum;
  403. latestData.pressure = new_press;
  404. datosAntiguos = latestData;
  405. xSemaphoreGive(dataMutex);
  406. }
  407. FILE *f = fopen(filename, "a");
  408. if (f) {
  409. //Crear la string para escribir en el archivo
  410. fprintf(f, "\t\t\t<trkpt lat=\"");
  411. fprintf(f, "%2.4f", datosAntiguos.latitude);
  412. fprintf(f, "\" lon=\"");
  413. fprintf(f, "%2.4f", datosAntiguos.longitude);
  414. fprintf(f, "\">\n");
  415. fprintf(f, "\t\t\t\t<ele>");
  416. fprintf(f, "%f", datosAntiguos.altura);
  417. fprintf(f, "</ele>\n");
  418. fprintf(f, "\t\t\t\t<time>");
  419. fprintf(f, "%s", datosAntiguos.tiempo);
  420. fprintf(f, "</time>\n");
  421. fprintf(f, "\t\t\t\t<speed>");
  422. fprintf(f, "%f", datosAntiguos.velocidad);
  423. fprintf(f, "</speed>\n");
  424. fprintf(f, "\t\t\t\t<extensions>\n");
  425. fprintf(f, "\t\t\t\t\t<gpxtpx:TrackPointExtension>\n");
  426. fprintf(f, "\t\t\t\t\t\t<gpxtpx:atemp>");
  427. fprintf(f, "%f", datosAntiguos.temperature);
  428. fprintf(f, "</gpxtpx:atemp>\n");
  429. fprintf(f, "\t\t\t\t\t</gpxtpx:TrackPointExtension>\n");
  430. fprintf(f, "\t\t\t\t\t<custom:humidity>");
  431. fprintf(f, "%f", datosAntiguos.humidity);
  432. fprintf(f, "</custom:humidity>\n");
  433. fprintf(f, "\t\t\t\t\t<custom:pressure>");
  434. fprintf(f, "%f", datosAntiguos.pressure);
  435. fprintf(f, "</custom:pressure>\n");
  436. fprintf(f, "\t\t\t\t</extensions>\n");
  437. fprintf(f, "\t\t\t</trkpt>\n");
  438. fclose(f);
  439. }
  440. unsigned long elapsedMillis = pdTICKS_TO_MS(xTaskGetTickCount()) - startMillis;
  441. ESP_LOGI(GEN_TAG, "Elapsed millis: %d.", elapsedMillis);
  442. vTaskDelayUntil(&xLastWakeTime, pdMS_TO_TICKS(MEASUREMENT_INTERVAL_S*1000)); // Espera x*1000 milisegundos
  443. }
  444. }
  445. void crear_archivo(){
  446. int num = 1;
  447. char nombre[32];
  448. snprintf(nombre, sizeof(nombre), "data%03d.gpx", num);
  449. snprintf(filename, sizeof(filename), "%s/%s", MOUNT_POINT, nombre);
  450. FILE *f = fopen(filename, "r");
  451. while (f != NULL) {
  452. fclose(f);
  453. num++;
  454. snprintf(nombre, sizeof(nombre), "data%03d.gpx", num);
  455. snprintf(filename, sizeof(filename), "%s/%s", MOUNT_POINT, nombre);
  456. f = fopen(filename, "r");
  457. }
  458. fclose(f);
  459. f = fopen(filename, "w");
  460. char buffer[50];
  461. if (f) {
  462. fprintf(f, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  463. "<gpx creator=\"ESP32 GPS LOGGER\" version=\"1.1\"\n"
  464. "\txmlns=\"http://www.topografix.com/GPX/1/1\"\n"
  465. "\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  466. "\txmlns:gpxtpx=\"http://www.garmin.com/xmlschemas/TrackPointExtension/v2\"\n"
  467. "\txmlns:gpxdata=\"http://www.cluetrust.com/XML/GPXDATA/1/0\"\n"
  468. "\txsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd\">\n"
  469. "\t<metadata>\n"
  470. "\t\t<name>Ruta grabada con ESP32 GPS Logger</name>\n"
  471. "\t\t<time>\n");
  472. 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),
  473. gps_date_day(&gps.date), gps_time_hour(&gps.time), gps_time_minute(&gps.time),
  474. gps_time_second(&gps.time), gps_time_centisecond(&gps.time));
  475. if (new_fecha_len < 0) {
  476. buffer[0] = '\0';
  477. }
  478. fprintf(f, "%s", buffer);
  479. fprintf(f, "</time>\n\t</metadata>\n"
  480. "\t<trk>\n"
  481. "\t\t<name>Rutita</name>\n"
  482. "\t\t<type>hiking</type>\n"
  483. "\t\t<trkseg>\n");
  484. fclose(f);
  485. } else {
  486. OLED_print("Error","creando archivo");
  487. vTaskDelay(pdMS_TO_TICKS(2000));
  488. crear_archivo();
  489. }
  490. }
  491. void cerrar_archivo() {
  492. FILE *f = fopen(filename, "w");
  493. if (f){
  494. fprintf(f, "\t\t</trkseg>\n\t</trk>\n</gpx>");
  495. fclose(f);
  496. }
  497. //int num = 1;
  498. //sprintf(filename, "/data%03d.gpx", num);
  499. //while (SD.exists(filename)) {
  500. // num++;
  501. // sprintf(filename, "/data%03d.gpx", num);
  502. //}
  503. }
  504. void activarWiFi(void)
  505. {
  506. OLED_print("WiFi", "Activando...");
  507. ESP_ERROR_CHECK(wifi_ap_init());
  508. char ip_str[16] = {0};
  509. get_ap_ip(ip_str, sizeof(ip_str));
  510. OLED_print("WiFi Activo", ip_str);
  511. vTaskDelay(pdMS_TO_TICKS(2000));
  512. ESP_ERROR_CHECK(iniciar_servidor_http());
  513. wifiActivado = true;
  514. wifiLastActivity = xTaskGetTickCount();
  515. }
  516. void desactivarWiFi(void)
  517. {
  518. if (http_server) {
  519. httpd_stop(http_server);
  520. http_server = NULL;
  521. }
  522. ESP_ERROR_CHECK(esp_wifi_stop());
  523. ESP_ERROR_CHECK(esp_wifi_deinit());
  524. if (ap_netif) {
  525. esp_netif_destroy(ap_netif);
  526. ap_netif = NULL;
  527. }
  528. wifiActivado = false;
  529. OLED_print("WiFi", "Apagado");
  530. }
  531. void IRAM_ATTR isr_button(void *arg) {
  532. unsigned long now = pdTICKS_TO_MS(xTaskGetTickCount());
  533. if (now < ignore_isr_until) {
  534. return; // Ignorar interrupción si está dentro del período de debounce
  535. }
  536. static unsigned long lastInterrupt = 0;
  537. if ((now - lastInterrupt) > 300 ){ // debounce de 300 ms
  538. BaseType_t xHigherPriorityTaskWoken = pdFALSE;
  539. xSemaphoreGiveFromISR(buttonSemaphore, &xHigherPriorityTaskWoken);
  540. lastInterrupt = now;
  541. if (xHigherPriorityTaskWoken) {
  542. portYIELD_FROM_ISR();
  543. }
  544. }
  545. }
  546. void drawProgressBar(int x, int y, int w, int h, unsigned long progress, unsigned long total) {
  547. int filledWidth = (progress * w) / total;
  548. ESP_ERROR_CHECK(ssd1306_draw_rect(d, x, y, filledWidth, h, true)); //dibuja un trozo de rectangulo relleno
  549. ESP_ERROR_CHECK(ssd1306_draw_rect(d, x + filledWidth, y, w - filledWidth, h, false)); //dibuja el resto del rectangulo vacio
  550. ESP_ERROR_CHECK(ssd1306_display(d));
  551. }
  552. void task_ui(void *pvParameters){
  553. unsigned long pressTime = 0;
  554. unsigned long lastActivity = pdTICKS_TO_MS(xTaskGetTickCount());
  555. bool pantallaOn = true; //comprobar el estado inicial, no se cual sera
  556. bool processingButton = false;
  557. while(1){
  558. if (xSemaphoreTake(buttonSemaphore, pdMS_TO_TICKS(200)) == pdTRUE){ //button pressed
  559. if (processingButton) continue; //evita reentradas
  560. processingButton = true;
  561. pressTime = pdTICKS_TO_MS(xTaskGetTickCount());
  562. lastActivity = pdTICKS_TO_MS(xTaskGetTickCount()); //reset watchdog
  563. if (!pantallaOn){
  564. uint8_t cmd_on[] = {0x00, 0xAF};
  565. i2c_master_transmit(i2c_dev_handle, cmd_on, sizeof(cmd_on), pdMS_TO_TICKS(100));
  566. pantallaOn = true;
  567. }
  568. bool timed_out = false;
  569. unsigned long checkTime = pdTICKS_TO_MS(xTaskGetTickCount());
  570. while (gpio_get_level(PIN_BUTTON) == 0){
  571. vTaskDelay(pdMS_TO_TICKS(10));
  572. checkTime = pdTICKS_TO_MS(xTaskGetTickCount());
  573. if ((checkTime - pressTime) > DURACION_WATCHDOG_MS){ //10s timeout para evitar bloqueos
  574. timed_out = true;
  575. break;
  576. }
  577. drawProgressBar(0, 64 - 10, 128, 8, checkTime - pressTime, PULSACION_LARGA_MS);
  578. }
  579. ignore_isr_until = pdTICKS_TO_MS(xTaskGetTickCount()) + 500; //ignorar nuevas interrupciones durante 500 ms
  580. unsigned long duration = checkTime - pressTime;
  581. if (timed_out){
  582. OLED_print("Apagando","pantalla");
  583. uint8_t cmd_off[] = {0x00, 0xAE};
  584. i2c_master_transmit(i2c_dev_handle, cmd_off, sizeof(cmd_off), pdMS_TO_TICKS(100));
  585. pantallaOn = false;
  586. } else {
  587. if (grabando){
  588. if (duration >= PULSACION_LARGA_MS){
  589. grabando = false;
  590. vTaskSuspend(medicionesHandle);
  591. OLED_print("Ruta","pausada");
  592. } else {
  593. pantallaEstado_grab = (pantallaEstado_grab + 1) % 5; //cicla entre 0-4
  594. struct SensorData currentData;
  595. if(xSemaphoreTake(dataMutex, portMAX_DELAY) == pdTRUE){
  596. currentData = latestData;
  597. xSemaphoreGive(dataMutex);
  598. }
  599. switch (pantallaEstado_grab){
  600. char line2[32];
  601. case 0:
  602. snprintf(line2, sizeof(line2), "%.4f,%.4f", currentData.longitude, currentData.latitude);
  603. OLED_print("Posicion", line2);
  604. break;
  605. case 1:
  606. snprintf(line2, sizeof(line2), "%.1fkm", distancia_total);
  607. OLED_print("Distancia", line2);
  608. break;
  609. case 2:
  610. snprintf(line2, sizeof(line2), "%.1fm", currentData.altura);
  611. OLED_print("Altitud", line2);
  612. break;
  613. case 3:
  614. snprintf(line2, sizeof(line2), "%.1fC/%.1f%%", currentData.temperature, currentData.humidity);
  615. OLED_print("Temp/Hum", line2);
  616. break;
  617. case 4:
  618. snprintf(line2, sizeof(line2), "%.1fkm/h", currentData.velocidad);
  619. OLED_print("Velocidad", line2);
  620. break;
  621. }
  622. }
  623. } else {
  624. if (duration >= PULSACION_LARGA_MS){
  625. switch (pantallaEstado_menu){
  626. case 0:
  627. //activar la ruta y crear el archivo
  628. crear_archivo();
  629. vTaskResume(medicionesHandle);
  630. OLED_print("Ruta","iniciada");
  631. finalizado = false;
  632. grabando = true;
  633. break;
  634. case 1:
  635. //cerrar el archivo y cambiar el valor de 'filename'
  636. cerrar_archivo();
  637. finalizado = true;
  638. break;
  639. case 2:
  640. //implementacion wifi
  641. if(!wifiActivado){
  642. activarWiFi();
  643. } else {
  644. desactivarWiFi();
  645. }
  646. break;
  647. }
  648. } else {
  649. pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
  650. int previous_state = -1;
  651. while (pantallaEstado_menu != previous_state) {
  652. previous_state = pantallaEstado_menu;
  653. switch (pantallaEstado_menu) {
  654. case 0:
  655. if (!finalizado) OLED_print("Reanudar","ruta");
  656. else OLED_print("Iniciar","ruta");
  657. break;
  658. case 1:
  659. FILE *f = fopen(filename, "r");
  660. if (f && !finalizado) {
  661. OLED_print("Finalizar","ruta");
  662. break;
  663. } else {
  664. pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
  665. }
  666. break;
  667. case 2:
  668. if (finalizado) {
  669. OLED_print("Conexion","WiFi");
  670. break;
  671. } else {
  672. pantallaEstado_menu = (pantallaEstado_menu + 1) % 3;
  673. }
  674. break;
  675. }
  676. }
  677. }
  678. }
  679. }
  680. lastActivity = pdTICKS_TO_MS(xTaskGetTickCount()); //reset watchdog
  681. processingButton = false;
  682. vTaskDelay(pdMS_TO_TICKS(100)); //pequeño delay para no busy waiting
  683. }
  684. //check watchdog fuera del boton
  685. if (pantallaOn && ((pdTICKS_TO_MS(xTaskGetTickCount()) - lastActivity) > DURACION_WATCHDOG_MS)){
  686. uint8_t cmd_off[] = {0x00, 0xAE};
  687. i2c_master_transmit(i2c_dev_handle, cmd_off, sizeof(cmd_off), pdMS_TO_TICKS(100));
  688. pantallaOn = false;
  689. }
  690. //check wifi timeout
  691. if (wifiActivado) {
  692. // server.handleClient() → NO necesario, httpd corre en su propio task
  693. // WiFi.softAPgetStationNum() → esp_wifi_ap_get_sta_list()
  694. wifi_sta_list_t sta_list;
  695. if (esp_wifi_ap_get_sta_list(&sta_list) == ESP_OK && sta_list.num > 0) {
  696. wifiLastActivity = pdTICKS_TO_MS(xTaskGetTickCount());
  697. }
  698. if ((pdTICKS_TO_MS(xTaskGetTickCount()) - wifiLastActivity) > WIFI_TIMEOUT_MS) {
  699. desactivarWiFi();
  700. }
  701. }
  702. }
  703. }
  704. void app_main(void) {
  705. gpio_config(&btn_cfg);
  706. // Instalar el servicio de interrupciones y adjuntar la ISR
  707. gpio_install_isr_service(0);
  708. gpio_isr_handler_add(PIN_BUTTON, isr_button, NULL);
  709. buttonSemaphore = xSemaphoreCreateBinary();
  710. dataMutex = xSemaphoreCreateMutex();
  711. // OLED check
  712. OLED_test();
  713. vTaskDelay(pdMS_TO_TICKS(1000));
  714. // DHT check
  715. DHT_test();
  716. vTaskDelay(pdMS_TO_TICKS(1000));
  717. // SD Card check
  718. SD_test();
  719. vTaskDelay(pdMS_TO_TICKS(1000));
  720. // GPS check
  721. GPS_test_wait();
  722. vTaskDelay(pdMS_TO_TICKS(2000));
  723. // Crear tarea para mediciones
  724. xTaskCreatePinnedToCore(
  725. task_mediciones, // Función de la tarea
  726. "Mediciones", // Nombre de la tarea
  727. 8192, // Tamaño del stack
  728. NULL, // Parámetro de la tarea
  729. 10, // Prioridad de la tarea
  730. &medicionesHandle, // Handle de la tarea
  731. 0 // Núcleo donde se ejecuta
  732. );
  733. xTaskCreatePinnedToCore(
  734. task_ui, // Función de la tarea
  735. "UI", // Nombre de la tarea
  736. 8192, // Tamaño del stack
  737. NULL, // Parámetro de la tarea
  738. 5, // Prioridad de la tarea
  739. NULL, // Handle de la tarea
  740. 1 // Núcleo donde se ejecuta
  741. );
  742. esp_pm_config_t pm_config = {
  743. .max_freq_mhz = 240,
  744. .min_freq_mhz = 80,
  745. .light_sleep_enable = true
  746. };
  747. esp_err_t err = esp_pm_configure(&pm_config);
  748. if (err != ESP_OK) {
  749. ESP_LOGE("General", "Error configuring power management");
  750. }
  751. ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE)); // Desactiva ahorro de energía WiFi
  752. vTaskSuspend(medicionesHandle); //inicia suspendida
  753. }