Files
RoboMovel/software/firmware/RoboMovel_ESP32CAM/RoboMovel_ESP32CAM.ino
T
mguinhos 23479241d8 Base movel: anticolisao com ESP32-CAM e Depth Anything V2 na VPS
- Firmware da base (ota-6): rede RoboMovel-Link no boot para trocar redes com a
  camera (POST /link, so na rede local), teto de velocidade para frente vindo da
  visao (POST /obstaculo, expira sozinho) e POST /anticolisao.
- Firmware novo da ESP32-CAM (OTA robomovel-cam): pega as redes da base, segue a
  rede dela e entrega JPEG sob demanda no canal robomovel-cam do pipe.
- visao-anticolisao: servico na VPS (Depth Anything V2 metrico indoor, CPU) que
  limita a velocidade do robo e serve estado/imagens no canal robomovel-visao;
  ponte_camera_lan.py para cameras sem o firmware novo.
- pipe.ovelha.cloud: repassa mensagens binarias e respostas com imagem.
- App joystick 0.2.0: mapa de profundidade/camera, distancias, botoes de
  anticolisao e de parear a camera.
2026-11-12 15:46:44 -03:00

491 lines
17 KiB
Arduino

// RoboMovel - ESP32-CAM (AI-Thinker) montada na base, olho da anticolisao
//
// Ao ligar:
// 1. Procura o Wi-Fi "RoboMovel-Link" que a base D1 R32 abre no boot (3 min). Entra, faz
// POST http://192.168.4.1/link com as redes que conhece e recebe as da base e a rede em
// que ela esta. As duas placas passam a conhecer as mesmas redes.
// 2. Conecta na rede da base (de preferencia) ou em outra conhecida. A cada 60 s acha a base
// na rede (UDP "ROBOMOVEL?" porta 4210) e repete a troca pelo /link, agora pela rede normal.
// Se a base estiver em outra rede conhecida, a camera muda para ela.
// 3. Entra no canal wss://pipe.ovelha.cloud/ws/robomovel-cam. Quando alguem manda o texto
// "quadro", responde com um JPEG em binario (o servico visao.py da VPS pede um por vez).
// Pedidos HTTP em https://pipe.ovelha.cloud/c/robomovel-cam/<rota>: /status,
// /flash?on=0|1, /config?res=qqvga|qvga|vga&q=10..40, /sincronizar
//
// Rede local: http://<ip>/ (pagina), /status, /flash?on=0|1
// http://<ip>:81/foto e :81/stream (MJPEG)
// OTA: host robomovel-cam, sem senha (./ota.sh). Grave pelo USB uma vez com o esquema de
// particao "Minimal SPIFFS (1.9MB APP with OTA)"; o ota.sh usa o mesmo.
//
// Arquivos fora do git: redes_padrao.h (mesmo da base) e link_senha.h (igual nas duas placas).
#include "esp_camera.h"
#include <WiFi.h>
#include <WiFiUdp.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <Preferences.h>
#include <ArduinoOTA.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include "redes_padrao.h"
#include "link_senha.h"
const char *FW_VERSION = "cam-1";
const char *LINK_SSID = "RoboMovel-Link";
const uint16_t PORTA_DESCOBERTA = 4210;
const int MAX_REDES = 5;
const unsigned long TENTATIVA_MS = 12000;
const unsigned long ESPERA_FALHA_MS = 15000;
const unsigned long SYNC_MS = 60000;
// Pinos da AI-Thinker ESP32-CAM
#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
#define FLASH_LED_PIN 4
#define RED_LED_PIN 33 // LOW = aceso
WebServer server(80);
WebSocketsClient canal;
Preferences prefs;
WiFiUDP udp;
String redeSsid[MAX_REDES], redeSenha[MAX_REDES];
int numRedes = 0;
String preferida; // rede em que a base estava na ultima troca
String roboIp;
bool flashLigado = false;
bool cameraOk = false;
bool otaPronto = false, otaAtivo = false;
bool canalIniciado = false;
volatile bool pedirQuadro = false;
uint32_t quadrosEnviados = 0;
bool estavaConectado = false, tentando = false;
int tentativa = 0;
unsigned long inicioTentativa = 0, esperarAte = 0, proximaSync = 0, ultimaSyncOk = 0;
// ------------------------------------------------------------------ redes salvas
void salvarRedes() {
prefs.putInt("n", numRedes);
for (int i = 0; i < MAX_REDES; i++) {
String s = "s" + String(i), p = "p" + String(i);
if (i < numRedes) {
prefs.putString(s.c_str(), redeSsid[i]);
prefs.putString(p.c_str(), redeSenha[i]);
} else {
prefs.remove(s.c_str());
prefs.remove(p.c_str());
}
}
prefs.putString("pref", preferida);
}
void carregarRedes() {
numRedes = constrain(prefs.getInt("n", 0), 0, MAX_REDES);
for (int i = 0; i < numRedes; i++) {
redeSsid[i] = prefs.getString(("s" + String(i)).c_str(), "");
redeSenha[i] = prefs.getString(("p" + String(i)).c_str(), "");
}
preferida = prefs.getString("pref", "");
}
int indiceRede(const String &ssid) {
for (int i = 0; i < numRedes; i++) if (redeSsid[i] == ssid) return i;
return -1;
}
// Rede nova entra; rede conhecida tem a senha atualizada (a da outra placa pode ser mais nova).
bool juntarRede(const String &ssid, const String &senha) {
if (ssid.length() < 1 || ssid.length() > 32 || senha.length() > 63 || ssid == LINK_SSID) return false;
int i = indiceRede(ssid);
if (i >= 0) {
if (redeSenha[i] == senha) return false;
redeSenha[i] = senha;
return true;
}
if (numRedes >= MAX_REDES) return false;
redeSsid[numRedes] = ssid;
redeSenha[numRedes] = senha;
numRedes++;
return true;
}
// ------------------------------------------------------------------ troca com a base
// POST /link na base. Devolve true se a troca deu certo.
bool trocarRedes(const String &ip) {
JsonDocument pedido;
pedido["chave"] = LINK_SENHA;
pedido["ip"] = WiFi.localIP().toString();
pedido["rssi"] = WiFi.RSSI();
JsonArray redes = pedido["redes"].to<JsonArray>();
for (int i = 0; i < numRedes; i++) {
JsonArray r = redes.add<JsonArray>();
r.add(redeSsid[i]);
r.add(redeSenha[i]);
}
String corpo;
serializeJson(pedido, corpo);
HTTPClient http;
http.setTimeout(3000);
if (!http.begin("http://" + ip + "/link")) return false;
http.addHeader("Content-Type", "application/json");
int codigo = http.POST(corpo);
String texto = codigo == 200 ? http.getString() : "";
http.end();
if (codigo != 200) {
Serial.printf("Link com a base em %s falhou (%d)\n", ip.c_str(), codigo);
return false;
}
JsonDocument resposta;
if (deserializeJson(resposta, texto)) return false;
bool mudou = false;
for (JsonArray r : resposta["redes"].as<JsonArray>()) {
if (juntarRede(r[0] | "", r[1] | "")) mudou = true;
}
String atual = resposta["atual"] | "";
if (atual.length() && atual != preferida) { preferida = atual; mudou = true; }
if (mudou) salvarRedes();
String rip = resposta["robo_ip"] | "";
if (rip.length()) roboIp = rip;
Serial.printf("Link ok: %d redes, base na rede \"%s\"\n", numRedes, preferida.c_str());
return true;
}
// Entra no RoboMovel-Link, troca as redes e sai. Bloqueia ate ~20 s.
bool sincronizarPeloAp() {
WiFi.disconnect();
int n = WiFi.scanNetworks();
bool achou = false;
for (int i = 0; i < n; i++) if (WiFi.SSID(i) == LINK_SSID) achou = true;
WiFi.scanDelete();
if (!achou) return false;
Serial.println("Achei o RoboMovel-Link");
WiFi.begin(LINK_SSID, LINK_SENHA);
unsigned long t0 = millis();
while (WiFi.status() != WL_CONNECTED && millis() - t0 < 10000) delay(100);
bool ok = WiFi.status() == WL_CONNECTED && trocarRedes("192.168.4.1");
WiFi.disconnect();
delay(200);
return ok;
}
// Na rede normal: acha a base por broadcast UDP e troca as redes.
void sincronizarNaRede() {
udp.beginPacket(IPAddress(255, 255, 255, 255), PORTA_DESCOBERTA);
udp.print("ROBOMOVEL?");
udp.endPacket();
unsigned long t0 = millis();
String ip;
while (millis() - t0 < 1000) {
if (udp.parsePacket() > 0) {
ip = udp.remoteIP().toString();
while (udp.available()) udp.read();
break;
}
delay(10);
}
if (!ip.length()) ip = roboIp; // broadcast perdido: tenta o ultimo IP conhecido
if (!ip.length()) return;
if (!trocarRedes(ip)) return;
roboIp = ip;
ultimaSyncOk = millis();
// Mesma rede que a base, se ela estiver numa rede que a camera conhece
if (preferida.length() && WiFi.SSID() != preferida && indiceRede(preferida) >= 0) {
Serial.printf("Base esta em \"%s\": trocando de rede\n", preferida.c_str());
WiFi.disconnect();
}
}
// ------------------------------------------------------------------ Wi-Fi
int redeDaTentativa(int k) {
int pref = indiceRede(preferida);
if (pref < 0) return k;
if (k == 0) return pref;
return (k - 1 < pref) ? k - 1 : k;
}
void iniciarOta() {
ArduinoOTA.setHostname("robomovel-cam");
ArduinoOTA.onStart([]() { otaAtivo = true; Serial.println("OTA: iniciando"); });
ArduinoOTA.onEnd([]() { Serial.println("OTA: concluido"); });
ArduinoOTA.onError([](ota_error_t e) { otaAtivo = false; Serial.printf("OTA: erro %u\n", e); });
ArduinoOTA.begin();
otaPronto = true;
}
void atualizarWifi() {
unsigned long agora = millis();
if (WiFi.status() == WL_CONNECTED) {
if (!estavaConectado) {
estavaConectado = true;
tentando = false;
tentativa = 0;
Serial.printf("Conectado em %s | IP %s | %d dBm\n", WiFi.SSID().c_str(),
WiFi.localIP().toString().c_str(), WiFi.RSSI());
iniciarOta();
iniciarCanal();
udp.begin(PORTA_DESCOBERTA + 1);
proximaSync = agora + 2000;
digitalWrite(RED_LED_PIN, LOW);
}
if ((long)(agora - proximaSync) >= 0) {
proximaSync = agora + SYNC_MS;
sincronizarNaRede();
}
return;
}
if (estavaConectado) {
estavaConectado = false;
if (otaPronto) ArduinoOTA.end();
otaPronto = false;
digitalWrite(RED_LED_PIN, HIGH);
Serial.println("Wi-Fi perdido");
}
if (tentando && agora - inicioTentativa < TENTATIVA_MS) return;
tentando = false;
if ((long)(agora - esperarAte) < 0) return;
if (tentativa >= numRedes) {
tentativa = 0;
// Nenhuma rede funcionou: talvez a base saiba de outra
if (!sincronizarPeloAp()) esperarAte = millis() + ESPERA_FALHA_MS;
return;
}
int i = redeDaTentativa(tentativa++);
Serial.printf("Tentando %s\n", redeSsid[i].c_str());
WiFi.begin(redeSsid[i].c_str(), redeSenha[i].c_str());
tentando = true;
inicioTentativa = agora;
}
// ------------------------------------------------------------------ camera
bool iniciarCamera() {
camera_config_t c = {};
c.ledc_channel = LEDC_CHANNEL_0;
c.ledc_timer = LEDC_TIMER_0;
c.pin_d0 = Y2_GPIO_NUM; c.pin_d1 = Y3_GPIO_NUM; c.pin_d2 = Y4_GPIO_NUM; c.pin_d3 = Y5_GPIO_NUM;
c.pin_d4 = Y6_GPIO_NUM; c.pin_d5 = Y7_GPIO_NUM; c.pin_d6 = Y8_GPIO_NUM; c.pin_d7 = Y9_GPIO_NUM;
c.pin_xclk = XCLK_GPIO_NUM; c.pin_pclk = PCLK_GPIO_NUM;
c.pin_vsync = VSYNC_GPIO_NUM; c.pin_href = HREF_GPIO_NUM;
c.pin_sccb_sda = SIOD_GPIO_NUM; c.pin_sccb_scl = SIOC_GPIO_NUM;
c.pin_pwdn = PWDN_GPIO_NUM; c.pin_reset = RESET_GPIO_NUM;
c.xclk_freq_hz = 20000000;
c.pixel_format = PIXFORMAT_JPEG;
c.grab_mode = CAMERA_GRAB_LATEST;
// QVGA: o Wi-Fi da camera dentro da base e fraco; quadros pequenos chegam mais rapido.
c.frame_size = FRAMESIZE_QVGA;
c.jpeg_quality = 14;
c.fb_count = psramFound() ? 2 : 1;
c.fb_location = psramFound() ? CAMERA_FB_IN_PSRAM : CAMERA_FB_IN_DRAM;
if (esp_camera_init(&c) != ESP_OK) return false;
return true;
}
bool configurarCamera(const String &res, int q) {
sensor_t *s = esp_camera_sensor_get();
if (!s) return false;
if (res == "qqvga") s->set_framesize(s, FRAMESIZE_QQVGA);
else if (res == "qvga") s->set_framesize(s, FRAMESIZE_QVGA);
else if (res == "vga") s->set_framesize(s, FRAMESIZE_VGA);
else if (res.length()) return false;
if (q >= 10 && q <= 40) s->set_quality(s, q);
return true;
}
void ligarFlash(bool on) {
flashLigado = on;
digitalWrite(FLASH_LED_PIN, on ? HIGH : LOW);
}
// Servidor proprio na porta 81 para foto e video (fora do WebServer, que e sincrono).
void enviarFoto(WiFiClient &c) {
camera_fb_t *fb = esp_camera_fb_get();
if (!fb) { c.print("HTTP/1.1 500 Erro\r\nConnection: close\r\n\r\n"); return; }
c.printf("HTTP/1.1 200 OK\r\nContent-Type: image/jpeg\r\nContent-Length: %u\r\n"
"Access-Control-Allow-Origin: *\r\nConnection: close\r\n\r\n", fb->len);
c.write(fb->buf, fb->len);
esp_camera_fb_return(fb);
}
void enviarVideo(WiFiClient &c, WiFiServer &srv) {
c.print("HTTP/1.1 200 OK\r\nContent-Type: multipart/x-mixed-replace; boundary=frame\r\n"
"Access-Control-Allow-Origin: *\r\n\r\n");
while (c.connected() && !srv.hasClient() && !otaAtivo) {
camera_fb_t *fb = esp_camera_fb_get();
if (!fb) break;
c.printf("--frame\r\nContent-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n", fb->len);
c.write(fb->buf, fb->len);
c.print("\r\n");
esp_camera_fb_return(fb);
vTaskDelay(1);
}
}
void tarefaCamera(void *) {
WiFiServer srv(81);
srv.begin();
for (;;) {
WiFiClient c = srv.accept();
if (!c) { vTaskDelay(pdMS_TO_TICKS(20)); continue; }
c.setTimeout(2);
String linha = c.readStringUntil('\n');
while (c.connected()) {
String h = c.readStringUntil('\n');
if (h.length() <= 1) break;
}
if (linha.startsWith("GET /foto")) enviarFoto(c);
else if (linha.startsWith("GET /stream")) enviarVideo(c, srv);
else c.print("HTTP/1.1 404 Nao encontrado\r\nConnection: close\r\n\r\n");
c.stop();
}
}
// ------------------------------------------------------------------ status e canal
String statusJson() {
JsonDocument d;
d["fw"] = FW_VERSION;
d["camera"] = cameraOk;
d["ssid"] = WiFi.status() == WL_CONNECTED ? WiFi.SSID() : "";
d["ip"] = WiFi.localIP().toString();
d["rssi"] = WiFi.RSSI();
d["rede_da_base"] = preferida;
d["robo_ip"] = roboIp;
d["redes"] = numRedes;
d["link_s"] = ultimaSyncOk ? (long)((millis() - ultimaSyncOk) / 1000) : -1;
d["canal"] = canal.isConnected();
d["quadros"] = quadrosEnviados;
d["flash"] = flashLigado;
d["psram_kb"] = ESP.getPsramSize() / 1024;
String s;
serializeJson(d, s);
return s;
}
void tratarCanal(uint8_t *dados, size_t tamanho) {
if (tamanho == 6 && memcmp(dados, "quadro", 6) == 0) {
pedirQuadro = true;
return;
}
JsonDocument pedido;
if (deserializeJson(pedido, dados, tamanho)) return;
if (strcmp(pedido["tipo"] | "", "req") != 0) return;
String rota = pedido["path"] | "/";
JsonObject q = pedido["query"].as<JsonObject>();
int codigo = 200;
String corpo;
if (rota == "/status") corpo = statusJson();
else if (rota == "/flash") { ligarFlash(String(q["on"] | "1") != "0"); corpo = statusJson(); }
else if (rota == "/config") {
if (configurarCamera(q["res"] | "", String(q["q"] | "0").toInt())) corpo = statusJson();
else { codigo = 400; corpo = "{\"error\":\"res: qqvga, qvga ou vga; q: 10 a 40\"}"; }
} else if (rota == "/sincronizar") { proximaSync = millis(); corpo = statusJson(); }
else { codigo = 404; corpo = "{\"error\":\"rota nao encontrada\"}"; }
JsonDocument resp;
resp["tipo"] = "resp";
resp["id"] = pedido["id"];
resp["status"] = codigo;
resp["body"] = corpo;
String texto;
serializeJson(resp, texto);
canal.sendTXT(texto);
}
void iniciarCanal() {
if (canalIniciado) return;
canal.onEvent([](WStype_t tipo, uint8_t *dados, size_t tamanho) {
if (tipo == WStype_TEXT) tratarCanal(dados, tamanho);
else if (tipo == WStype_CONNECTED) Serial.println("Canal robomovel-cam conectado");
else if (tipo == WStype_DISCONNECTED) Serial.println("Canal robomovel-cam desconectado");
});
canal.beginSSL("pipe.ovelha.cloud", 443, "/ws/robomovel-cam");
canal.setReconnectInterval(5000);
canal.enableHeartbeat(15000, 3000, 2);
canalIniciado = true;
}
void enviarQuadroPedido() {
if (!pedirQuadro || otaAtivo || !canal.isConnected()) return;
pedirQuadro = false;
camera_fb_t *fb = esp_camera_fb_get();
if (!fb) return;
canal.sendBIN(fb->buf, fb->len);
esp_camera_fb_return(fb);
quadrosEnviados++;
}
// ------------------------------------------------------------------ setup / loop
void setup() {
Serial.begin(115200);
pinMode(FLASH_LED_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
ligarFlash(false);
digitalWrite(RED_LED_PIN, HIGH);
Serial.printf("\nRoboMovel ESP32-CAM %s\n", FW_VERSION);
cameraOk = iniciarCamera();
if (!cameraOk) Serial.println("[ERRO] camera nao iniciou (cabo flat / alimentacao 5 V)");
prefs.begin("robocam", false);
carregarRedes();
bool mudou = false;
for (auto &r : DEFAULT_NETWORKS) {
if (indiceRede(r[0]) < 0 && juntarRede(r[0], r[1])) mudou = true;
}
if (mudou) salvarRedes();
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.setSleep(false);
WiFi.setAutoReconnect(false);
// A base pode demorar mais para subir o RoboMovel-Link: algumas tentativas
for (int i = 0; i < 3; i++) {
if (sincronizarPeloAp()) break;
delay(2000);
}
server.on("/", HTTP_GET, []() {
server.send(200, "text/html; charset=utf-8",
"<html><head><meta name='viewport' content='width=device-width'><title>RoboMovel CAM</title></head>"
"<body style='font-family:sans-serif;text-align:center;background:#222;color:#eee'>"
"<h3>RoboMovel CAM</h3><img id='v' style='max-width:100%'><p><a href='/status' style='color:#8cf'>status</a>"
" | <a href='/flash?on=1' style='color:#8cf'>flash on</a> | <a href='/flash?on=0' style='color:#8cf'>off</a></p>"
"<script>document.getElementById('v').src='http://'+location.hostname+':81/stream'</script></body></html>");
});
server.on("/status", HTTP_GET, []() { server.send(200, "application/json", statusJson()); });
server.on("/flash", HTTP_GET, []() {
ligarFlash(server.arg("on") != "0");
server.send(200, "application/json", statusJson());
});
server.begin();
if (cameraOk) xTaskCreatePinnedToCore(tarefaCamera, "camera", 8192, nullptr, 1, nullptr, 0);
}
void loop() {
atualizarWifi();
if (otaPronto) ArduinoOTA.handle();
server.handleClient();
if (canalIniciado) canal.loop();
enviarQuadroPedido();
delay(1);
}