that_one_nigga_you_k

codigo das placas (com ID, sem deep sleep)

Jun 26th, 2025
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 8.72 KB | None | 0 0
  1. #define TINY_GSM_DEBUG Serial
  2. #define TINY_GSM_MODEM_SIM800
  3.  
  4. #include <TinyGsmClient.h>
  5. #include "esp_camera.h"
  6. #include <cstdlib> // Para rand() e srand()
  7. #include <ctime>   // Para time_t, mktime, etc.
  8.  
  9. #define FLASH_PIN 4
  10. #define CAMERA_MODEL_AI_THINKER
  11.  
  12. // --- Pinos da Câmera ---
  13. #define PWDN_GPIO_NUM  32
  14. #define RESET_GPIO_NUM -1
  15. #define XCLK_GPIO_NUM  0
  16. #define SIOD_GPIO_NUM  26
  17. #define SIOC_GPIO_NUM  27
  18. #define Y9_GPIO_NUM    35
  19. #define Y8_GPIO_NUM    34
  20. #define Y7_GPIO_NUM    39
  21. #define Y6_GPIO_NUM    36
  22. #define Y5_GPIO_NUM    21
  23. #define Y4_GPIO_NUM    19
  24. #define Y3_GPIO_NUM    18
  25. #define Y2_GPIO_NUM    5
  26. #define VSYNC_GPIO_NUM 25
  27. #define HREF_GPIO_NUM  23
  28. #define PCLK_GPIO_NUM  22
  29.  
  30. // --- Pinos para SIM800L ---
  31. #define SIM800_RX_PIN 15
  32. #define SIM800_TX_PIN 13
  33. HardwareSerial SerialSIM(2);
  34.  
  35. // --- Configurações do Servidor ---
  36. const char NGROK_TCP_ADDRESS[] = "1.tcp.sa.ngrok.io";
  37. const int NGROK_TCP_PORT       = 21302;
  38.  
  39. // --- Endpoints do Servidor ---
  40. const char* REGISTER_PATH = "/register";
  41. const char* UPLOAD_PATH   = "/raw_upload";
  42. const char* COMMAND_PATH  = "/command";
  43.  
  44. // --- APN ---
  45. char apn[]  = "claro.com.br";
  46. char user[] = "claro";
  47. char pass[] = "claro";
  48.  
  49. // --- Variáveis Globais ---
  50. TinyGsm modem(SerialSIM);
  51. TinyGsmClient client(modem);
  52. char deviceID[14];
  53. unsigned long previousMillis_upload = 0;
  54. unsigned long previousMillis_command = 0;
  55. long uploadInterval = 8000;
  56. long commandInterval = 8000;
  57.  
  58. void geradorcripto(int tamanho, char* id_str) {
  59.     int digitos[tamanho];
  60.     for (int i = 0; i < tamanho; i++) {
  61.         digitos[i] = rand() % 10;
  62.     }
  63.     int soma1 = 0;
  64.     for (int i = 0; i < tamanho - 1; i++) {
  65.         soma1 += digitos[i] * (tamanho - 1 - i);
  66.     }
  67.     int digito1 = (soma1 * 10) % 11;
  68.     if (digito1 == 10) digito1 = 0;
  69.     int soma2 = 0;
  70.     for (int i = 0; i < tamanho; i++) {
  71.         soma2 += digitos[i] * (tamanho - i);
  72.     }
  73.     int digito2 = (soma2 * 10) % 11;
  74.     if (digito2 == 10) digito2 = 0;
  75.     for(int i=0; i<tamanho; i++) {
  76.       id_str[i] = digitos[i] + '0';
  77.     }
  78.     id_str[tamanho] = digito1 + '0';
  79.     id_str[tamanho+1] = digito2 + '0';
  80.     id_str[tamanho+2] = '\0';
  81. }
  82.  
  83. void configurarSeedAleatoriaViaGPRS() {
  84.   Serial.println("Buscando hora da rede para a semente aleatoria...");
  85.   int year, month, day, hour, min, sec;
  86.   float timezone;
  87.   time_t seed_time = 0;
  88.  
  89.   while (seed_time == 0) {
  90.     if (modem.getNetworkTime(&year, &month, &day, &hour, &min, &sec, &timezone)) {
  91.         struct tm t;
  92.         t.tm_year = year - 1900;
  93.         t.tm_mon = month - 1;
  94.         t.tm_mday = day;
  95.         t.tm_hour = hour;
  96.         t.tm_min = min;
  97.         t.tm_sec = sec;
  98.         seed_time = mktime(&t);
  99.  
  100.         if (seed_time != -1) {
  101.             Serial.print("Timestamp atual para seed: ");
  102.             Serial.println(seed_time);
  103.             srand(seed_time);
  104.             return;
  105.         }
  106.     }
  107.     Serial.println("Falha ao obter a hora. Tentando novamente em 5s...");
  108.     delay(5000);
  109.   }
  110. }
  111.  
  112.  
  113. bool registerDevice() {
  114.   Serial.println("Tentando registrar dispositivo...");
  115.   if (!client.connect(NGROK_TCP_ADDRESS, NGROK_TCP_PORT)) return false;
  116.   String body = "id=" + String(deviceID);
  117.   client.print(String("POST ") + REGISTER_PATH + " HTTP/1.1\r\n");
  118.   client.print(String("Host: ") + NGROK_TCP_ADDRESS + "\r\n");
  119.   client.print("Content-Type: application/x-www-form-urlencoded\r\n");
  120.   client.print("Content-Length: " + String(body.length()) + "\r\n\r\n");
  121.   client.print(body);
  122.   unsigned long timeout = millis();
  123.   while (client.connected() && !client.available() && millis() - timeout < 5000L);
  124.   if (client.available()) {
  125.     String line = client.readStringUntil('\n');
  126.     if (line.indexOf("200 OK") != -1) {
  127.       Serial.println("SUCESSO: Dispositivo registrado!");
  128.       client.stop();
  129.       return true;
  130.     }
  131.   }
  132.   Serial.println("FALHA: Nao foi possivel registrar.");
  133.   client.stop();
  134.   return false;
  135. }
  136.  
  137. bool setupCamera(){
  138.     camera_config_t config;
  139.     config.ledc_channel = LEDC_CHANNEL_0;
  140.     config.ledc_timer = LEDC_TIMER_0;
  141.     config.pin_d0 = Y2_GPIO_NUM;
  142.     config.pin_d1 = Y3_GPIO_NUM;
  143.     config.pin_d2 = Y4_GPIO_NUM;
  144.     config.pin_d3 = Y5_GPIO_NUM;
  145.     config.pin_d4 = Y6_GPIO_NUM;
  146.     config.pin_d5 = Y7_GPIO_NUM;
  147.     config.pin_d6 = Y8_GPIO_NUM;
  148.     config.pin_d7 = Y9_GPIO_NUM;
  149.     config.pin_xclk = XCLK_GPIO_NUM;
  150.     config.pin_pclk = PCLK_GPIO_NUM;
  151.     config.pin_vsync = VSYNC_GPIO_NUM;
  152.     config.pin_href = HREF_GPIO_NUM;
  153.     config.pin_sccb_sda = SIOD_GPIO_NUM;
  154.     config.pin_sccb_scl = SIOC_GPIO_NUM;
  155.     config.pin_pwdn = PWDN_GPIO_NUM;
  156.     config.pin_reset = RESET_GPIO_NUM;
  157.     config.xclk_freq_hz = 20000000;
  158.     config.pixel_format = PIXFORMAT_JPEG;
  159.     config.frame_size = FRAMESIZE_QVGA;
  160.     config.jpeg_quality = 12;
  161.     config.fb_count = 1;
  162.     esp_err_t err = esp_camera_init(&config);
  163.     if (err != ESP_OK) { return false; }
  164.     return true;
  165. }
  166.  
  167. void uploadPhoto() {
  168.     camera_fb_t *fb = esp_camera_fb_get();
  169.     if (!fb) { Serial.println("Falha ao capturar foto."); return; }
  170.    
  171.     if (!client.connect(NGROK_TCP_ADDRESS, NGROK_TCP_PORT)) {
  172.         esp_camera_fb_return(fb);
  173.         Serial.println("Falha ao conectar para upload.");
  174.         return;
  175.     }
  176.  
  177.     String path_with_id = String(UPLOAD_PATH) + "/" + String(deviceID);
  178.     client.print(String("POST ") + path_with_id + " HTTP/1.1\r\n");
  179.     client.print(String("Host: ") + NGROK_TCP_ADDRESS + "\r\n");
  180.     client.print(String("Content-Length: ") + String(fb->len) + "\r\n");
  181.     client.print("Content-Type: image/jpeg\r\n\r\n");
  182.    
  183.     // --- ENVIO ROBUSTO EM BLOCOS ---
  184.     size_t image_len = fb->len;
  185.     size_t total_sent = 0;
  186.     bool upload_failed = false;
  187.     while(total_sent < image_len) {
  188.         size_t chunk_size = 256;
  189.         if(total_sent + chunk_size > image_len) chunk_size = image_len - total_sent;
  190.         size_t sent = client.write(fb->buf + total_sent, chunk_size);
  191.         if(sent == 0) {
  192.             upload_failed = true;
  193.             break;
  194.         }
  195.         total_sent += sent;
  196.     }
  197.     esp_camera_fb_return(fb);
  198.  
  199.     if(upload_failed || total_sent != image_len) {
  200.         Serial.printf("!!! FALHA NO ENVIO da imagem. Enviado %d de %d bytes\n", total_sent, image_len);
  201.     } else {
  202.         Serial.printf("Foto enviada com sucesso (%d bytes).\n", total_sent);
  203.     }
  204.     client.stop();
  205. }
  206.  
  207. void getCommandFromServer() {
  208.   if (!client.connect(NGROK_TCP_ADDRESS, NGROK_TCP_PORT)) return;
  209.   String path_with_id = String(COMMAND_PATH) + "/" + String(deviceID);
  210.   client.print(String("GET ") + path_with_id + " HTTP/1.1\r\n");
  211.   client.print(String("Host: ") + NGROK_TCP_ADDRESS + "\r\n\r\n");
  212.   unsigned long timeout = millis();
  213.   while (!client.available() && millis() - timeout < 5000L);
  214.   String response_body = "";
  215.   if(client.available()){
  216.     if(client.find("\r\n\r\n")){ response_body = client.readString(); }
  217.   }
  218.   client.stop();
  219.   response_body.trim();
  220.   if (response_body.equalsIgnoreCase("FLASH_ON")) {
  221.     digitalWrite(FLASH_PIN, HIGH);
  222.     Serial.println("Comando: FLASH_ON");
  223.   } else if (response_body.equalsIgnoreCase("FLASH_OFF")) {
  224.     digitalWrite(FLASH_PIN, LOW);
  225.     Serial.println("Comando: FLASH_OFF");
  226.   }
  227. }
  228.  
  229. void setup() {
  230.   Serial.begin(115200);
  231.   delay(1000);
  232.  
  233.   pinMode(FLASH_PIN, OUTPUT);
  234.   digitalWrite(FLASH_PIN, LOW);
  235.  
  236.   if (!setupCamera()) ESP.restart();
  237.   Serial.println("Camera inicializada.");
  238.  
  239.   SerialSIM.begin(9600, SERIAL_8N1, SIM800_RX_PIN, SIM800_TX_PIN);
  240.   delay(3000);
  241.   Serial.println("Inicializando modem...");
  242.   if (!modem.init()) ESP.restart();
  243.   Serial.print("Modem: "); Serial.println(modem.getModemInfo());
  244.  
  245.   Serial.println("Conectando ao GPRS...");
  246.   while (!modem.gprsConnect(apn, user, pass)) {
  247.     Serial.println("Falha ao conectar GPRS. Tentando de novo em 10s.");
  248.     delay(10000);
  249.   }
  250.   Serial.println("GPRS Conectado!");
  251.  
  252.   configurarSeedAleatoriaViaGPRS();
  253.   geradorcripto(11, deviceID);
  254.  
  255.   Serial.println("\n===================================");
  256.   Serial.print("ID UNICO DO DISPOSITIVO: ");
  257.   Serial.println(deviceID);
  258.   Serial.println("===================================\n");
  259.  
  260.   while(!registerDevice()) {
  261.     Serial.println("Tentando registrar de novo em 10s...");
  262.     delay(10000);
  263.   }
  264. }
  265.  
  266. void loop() {
  267.   if (!modem.isGprsConnected()) {
  268.     if (!modem.gprsConnect(apn, user, pass)) {
  269.       delay(10000); return;
  270.     }
  271.   }
  272.   unsigned long currentMillis = millis();
  273.   if (currentMillis - previousMillis_upload >= uploadInterval) {
  274.     previousMillis_upload = currentMillis;
  275.     uploadPhoto();
  276.   }
  277.   if (currentMillis - previousMillis_command >= commandInterval) {
  278.     previousMillis_command = currentMillis;
  279.     getCommandFromServer();
  280.   }
  281.   delay(100);
  282. }
  283.  
Add Comment
Please, Sign In to add comment