Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define TINY_GSM_DEBUG Serial
- #define TINY_GSM_MODEM_SIM800
- #include <TinyGsmClient.h>
- #include "esp_camera.h"
- #include <cstdlib> // Para rand() e srand()
- #include <ctime> // Para time_t, mktime, etc.
- #define FLASH_PIN 4
- #define CAMERA_MODEL_AI_THINKER
- // --- Pinos da Câmera ---
- #define PWDN_GPIO_NUM 32
- #define RESET_GPIO_NUM -1
- #define XCLK_GPIO_NUM 0
- #define SIOD_GPIO_NUM 26
- #define SIOC_GPIO_NUM 27
- #define Y9_GPIO_NUM 35
- #define Y8_GPIO_NUM 34
- #define Y7_GPIO_NUM 39
- #define Y6_GPIO_NUM 36
- #define Y5_GPIO_NUM 21
- #define Y4_GPIO_NUM 19
- #define Y3_GPIO_NUM 18
- #define Y2_GPIO_NUM 5
- #define VSYNC_GPIO_NUM 25
- #define HREF_GPIO_NUM 23
- #define PCLK_GPIO_NUM 22
- // --- Pinos para SIM800L ---
- #define SIM800_RX_PIN 15
- #define SIM800_TX_PIN 13
- HardwareSerial SerialSIM(2);
- // --- Configurações do Servidor ---
- const char NGROK_TCP_ADDRESS[] = "1.tcp.sa.ngrok.io";
- const int NGROK_TCP_PORT = 21302;
- // --- Endpoints do Servidor ---
- const char* REGISTER_PATH = "/register";
- const char* UPLOAD_PATH = "/raw_upload";
- const char* COMMAND_PATH = "/command";
- // --- APN ---
- char apn[] = "claro.com.br";
- char user[] = "claro";
- char pass[] = "claro";
- // --- Variáveis Globais ---
- TinyGsm modem(SerialSIM);
- TinyGsmClient client(modem);
- char deviceID[14];
- unsigned long previousMillis_upload = 0;
- unsigned long previousMillis_command = 0;
- long uploadInterval = 8000;
- long commandInterval = 8000;
- void geradorcripto(int tamanho, char* id_str) {
- int digitos[tamanho];
- for (int i = 0; i < tamanho; i++) {
- digitos[i] = rand() % 10;
- }
- int soma1 = 0;
- for (int i = 0; i < tamanho - 1; i++) {
- soma1 += digitos[i] * (tamanho - 1 - i);
- }
- int digito1 = (soma1 * 10) % 11;
- if (digito1 == 10) digito1 = 0;
- int soma2 = 0;
- for (int i = 0; i < tamanho; i++) {
- soma2 += digitos[i] * (tamanho - i);
- }
- int digito2 = (soma2 * 10) % 11;
- if (digito2 == 10) digito2 = 0;
- for(int i=0; i<tamanho; i++) {
- id_str[i] = digitos[i] + '0';
- }
- id_str[tamanho] = digito1 + '0';
- id_str[tamanho+1] = digito2 + '0';
- id_str[tamanho+2] = '\0';
- }
- void configurarSeedAleatoriaViaGPRS() {
- Serial.println("Buscando hora da rede para a semente aleatoria...");
- int year, month, day, hour, min, sec;
- float timezone;
- time_t seed_time = 0;
- while (seed_time == 0) {
- if (modem.getNetworkTime(&year, &month, &day, &hour, &min, &sec, &timezone)) {
- struct tm t;
- t.tm_year = year - 1900;
- t.tm_mon = month - 1;
- t.tm_mday = day;
- t.tm_hour = hour;
- t.tm_min = min;
- t.tm_sec = sec;
- seed_time = mktime(&t);
- if (seed_time != -1) {
- Serial.print("Timestamp atual para seed: ");
- Serial.println(seed_time);
- srand(seed_time);
- return;
- }
- }
- Serial.println("Falha ao obter a hora. Tentando novamente em 5s...");
- delay(5000);
- }
- }
- bool registerDevice() {
- Serial.println("Tentando registrar dispositivo...");
- if (!client.connect(NGROK_TCP_ADDRESS, NGROK_TCP_PORT)) return false;
- String body = "id=" + String(deviceID);
- client.print(String("POST ") + REGISTER_PATH + " HTTP/1.1\r\n");
- client.print(String("Host: ") + NGROK_TCP_ADDRESS + "\r\n");
- client.print("Content-Type: application/x-www-form-urlencoded\r\n");
- client.print("Content-Length: " + String(body.length()) + "\r\n\r\n");
- client.print(body);
- unsigned long timeout = millis();
- while (client.connected() && !client.available() && millis() - timeout < 5000L);
- if (client.available()) {
- String line = client.readStringUntil('\n');
- if (line.indexOf("200 OK") != -1) {
- Serial.println("SUCESSO: Dispositivo registrado!");
- client.stop();
- return true;
- }
- }
- Serial.println("FALHA: Nao foi possivel registrar.");
- client.stop();
- return false;
- }
- bool setupCamera(){
- camera_config_t config;
- config.ledc_channel = LEDC_CHANNEL_0;
- config.ledc_timer = LEDC_TIMER_0;
- config.pin_d0 = Y2_GPIO_NUM;
- config.pin_d1 = Y3_GPIO_NUM;
- config.pin_d2 = Y4_GPIO_NUM;
- config.pin_d3 = Y5_GPIO_NUM;
- config.pin_d4 = Y6_GPIO_NUM;
- config.pin_d5 = Y7_GPIO_NUM;
- config.pin_d6 = Y8_GPIO_NUM;
- config.pin_d7 = Y9_GPIO_NUM;
- config.pin_xclk = XCLK_GPIO_NUM;
- config.pin_pclk = PCLK_GPIO_NUM;
- config.pin_vsync = VSYNC_GPIO_NUM;
- config.pin_href = HREF_GPIO_NUM;
- config.pin_sccb_sda = SIOD_GPIO_NUM;
- config.pin_sccb_scl = SIOC_GPIO_NUM;
- config.pin_pwdn = PWDN_GPIO_NUM;
- config.pin_reset = RESET_GPIO_NUM;
- config.xclk_freq_hz = 20000000;
- config.pixel_format = PIXFORMAT_JPEG;
- config.frame_size = FRAMESIZE_QVGA;
- config.jpeg_quality = 12;
- config.fb_count = 1;
- esp_err_t err = esp_camera_init(&config);
- if (err != ESP_OK) { return false; }
- return true;
- }
- void uploadPhoto() {
- camera_fb_t *fb = esp_camera_fb_get();
- if (!fb) { Serial.println("Falha ao capturar foto."); return; }
- if (!client.connect(NGROK_TCP_ADDRESS, NGROK_TCP_PORT)) {
- esp_camera_fb_return(fb);
- Serial.println("Falha ao conectar para upload.");
- return;
- }
- String path_with_id = String(UPLOAD_PATH) + "/" + String(deviceID);
- client.print(String("POST ") + path_with_id + " HTTP/1.1\r\n");
- client.print(String("Host: ") + NGROK_TCP_ADDRESS + "\r\n");
- client.print(String("Content-Length: ") + String(fb->len) + "\r\n");
- client.print("Content-Type: image/jpeg\r\n\r\n");
- // --- ENVIO ROBUSTO EM BLOCOS ---
- size_t image_len = fb->len;
- size_t total_sent = 0;
- bool upload_failed = false;
- while(total_sent < image_len) {
- size_t chunk_size = 256;
- if(total_sent + chunk_size > image_len) chunk_size = image_len - total_sent;
- size_t sent = client.write(fb->buf + total_sent, chunk_size);
- if(sent == 0) {
- upload_failed = true;
- break;
- }
- total_sent += sent;
- }
- esp_camera_fb_return(fb);
- if(upload_failed || total_sent != image_len) {
- Serial.printf("!!! FALHA NO ENVIO da imagem. Enviado %d de %d bytes\n", total_sent, image_len);
- } else {
- Serial.printf("Foto enviada com sucesso (%d bytes).\n", total_sent);
- }
- client.stop();
- }
- void getCommandFromServer() {
- if (!client.connect(NGROK_TCP_ADDRESS, NGROK_TCP_PORT)) return;
- String path_with_id = String(COMMAND_PATH) + "/" + String(deviceID);
- client.print(String("GET ") + path_with_id + " HTTP/1.1\r\n");
- client.print(String("Host: ") + NGROK_TCP_ADDRESS + "\r\n\r\n");
- unsigned long timeout = millis();
- while (!client.available() && millis() - timeout < 5000L);
- String response_body = "";
- if(client.available()){
- if(client.find("\r\n\r\n")){ response_body = client.readString(); }
- }
- client.stop();
- response_body.trim();
- if (response_body.equalsIgnoreCase("FLASH_ON")) {
- digitalWrite(FLASH_PIN, HIGH);
- Serial.println("Comando: FLASH_ON");
- } else if (response_body.equalsIgnoreCase("FLASH_OFF")) {
- digitalWrite(FLASH_PIN, LOW);
- Serial.println("Comando: FLASH_OFF");
- }
- }
- void setup() {
- Serial.begin(115200);
- delay(1000);
- pinMode(FLASH_PIN, OUTPUT);
- digitalWrite(FLASH_PIN, LOW);
- if (!setupCamera()) ESP.restart();
- Serial.println("Camera inicializada.");
- SerialSIM.begin(9600, SERIAL_8N1, SIM800_RX_PIN, SIM800_TX_PIN);
- delay(3000);
- Serial.println("Inicializando modem...");
- if (!modem.init()) ESP.restart();
- Serial.print("Modem: "); Serial.println(modem.getModemInfo());
- Serial.println("Conectando ao GPRS...");
- while (!modem.gprsConnect(apn, user, pass)) {
- Serial.println("Falha ao conectar GPRS. Tentando de novo em 10s.");
- delay(10000);
- }
- Serial.println("GPRS Conectado!");
- configurarSeedAleatoriaViaGPRS();
- geradorcripto(11, deviceID);
- Serial.println("\n===================================");
- Serial.print("ID UNICO DO DISPOSITIVO: ");
- Serial.println(deviceID);
- Serial.println("===================================\n");
- while(!registerDevice()) {
- Serial.println("Tentando registrar de novo em 10s...");
- delay(10000);
- }
- }
- void loop() {
- if (!modem.isGprsConnected()) {
- if (!modem.gprsConnect(apn, user, pass)) {
- delay(10000); return;
- }
- }
- unsigned long currentMillis = millis();
- if (currentMillis - previousMillis_upload >= uploadInterval) {
- previousMillis_upload = currentMillis;
- uploadPhoto();
- }
- if (currentMillis - previousMillis_command >= commandInterval) {
- previousMillis_command = currentMillis;
- getCommandFromServer();
- }
- delay(100);
- }
Add Comment
Please, Sign In to add comment