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.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-11-12 15:46:44 -03:00
1 parent 4b7f23503a
commit 1307da0228
17 files changed
+155516 -11

No files matched your search

@@ -14,6 +14,14 @@
// DELETE /wifi?ssid=NOME
// Canal publico: conecta em wss://pipe.ovelha.cloud/ws/robomovel e aceita a mesma API por
// https://pipe.ovelha.cloud/c/robomovel/<rota> (ex.: /c/robomovel/status), sem autenticacao.
// Anticolisao (servico visao na VPS, a partir da ESP32-CAM):
// POST /obstaculo?lim=PASSOS&ttl=MS&d=METROS&livre=LADO teto de velocidade para "frente"
// (0 = bloqueado) valido por ttl ms; sem atualizacao, o teto expira e o robo volta ao normal
// POST /anticolisao?on=0|1 liga/desliga o teto (padrao: ligado)
// Link com a ESP32-CAM: no boot (e por POST /link/abrir) abre o Wi-Fi "RoboMovel-Link" por 3 min.
// A camera entra nele (ou acha o robo na rede normal) e faz POST /link com JSON
// {"chave":LINK_SENHA,"ip":"...","redes":[["ssid","senha"],...]}; o robo junta as redes que nao
// conhece e responde com as dele e a rede atual. /link so existe na rede local (nao no pipe).
// Descoberta: responde ao texto "ROBOMOVEL?" em UDP 4210 (broadcast) com o JSON do /status.
// Atualizacao pela rede (OTA): host robomovel, sem senha (use ./ota.sh).
// Os motores param no inicio da gravacao.
@@ -39,6 +47,7 @@
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include "soc/gpio_reg.h"
#include "link_senha.h"
enum Wheel { FL, FR, RL, RR, WHEELS };
@@ -85,7 +94,7 @@ unsigned long lastRampMs = 0;
// ---- Wi-Fi ----
const int MAX_NETWORKS = 5;
const char *FW_VERSION = "ota-5";
const char *FW_VERSION = "ota-6";
// Redes padrao (SSID e senha), na ordem de tentativa, em redes_padrao.h (fora do git).
// Copie redes_padrao.exemplo.h para redes_padrao.h e preencha. Sao recadastradas a cada boot.
#include "redes_padrao.h"
@@ -93,6 +102,8 @@ const char *AP_SSID = "RoboMovel-Setup";
const unsigned long ATTEMPT_MS = 12000; // tempo para tentar cada rede
const unsigned long RETRY_MS = 30000; // espera apos falhar em todas
const unsigned long AP_GRACE_MS = 5000; // mantem o AP apos conectar
const char *LINK_SSID = "RoboMovel-Link";
const unsigned long LINK_JANELA_MS = 180000; // AP de link aberto apos o boot ou /link/abrir
Preferences prefs;
String savedSsid[MAX_NETWORKS];
@@ -104,6 +115,23 @@ WiFiUDP descoberta;
WebSocketsClient canal; // canal publico pipe.ovelha.cloud
const uint16_t PORTA_DESCOBERTA = 4210;
bool apOn = false;
bool apEhLink = false; // o AP ligado e o RoboMovel-Link (e nao o de configuracao)
unsigned long linkAteMs = 0;
String camIp;
long camRssi = 0;
unsigned long camVistoMs = 0;
bool camVista = false;
// ---- Anticolisao ----
const int DIR_FRENTE = 0;
const uint32_t MAX_TTL_MS = 3000;
bool anticolisao = true;
uint32_t limFrente = MAX_SPEED;
unsigned long obstAteMs = 0;
unsigned long obstRecebidoMs = 0;
bool obstRecebido = false;
float obstDist = -1;
String obstLivre;
bool wasConnected = false;
bool attempting = false;
bool forceAttempt = false;
@@ -140,6 +168,14 @@ void applyDirection(int d) {
appliedDir = d;
}
bool obstaculoValido() {
return anticolisao && obstRecebido && (long)(millis() - obstAteMs) < 0;
}
uint32_t tetoFrente() {
return obstaculoValido() ? limFrente : MAX_SPEED;
}
void requestStop() {
moving = false;
targetSpeed = 0;
@@ -156,6 +192,7 @@ void updateMotion() {
if (moving && moveViaSta && WiFi.status() != WL_CONNECTED) requestStop();
float desired = targetSpeed;
if (moving && requestedDir == DIR_FRENTE) desired = min(desired, (float)tetoFrente());
if (moving && requestedDir != appliedDir) {
if (currentSpeed <= 0) applyDirection(requestedDir);
else desired = 0;
@@ -206,7 +243,25 @@ String statusJson() {
s += "\",\"canal\":";
s += canal.isConnected() ? "true" : "false";
s += ",\"setup_ap\":";
s += apOn ? "true" : "false";
s += (apOn && !apEhLink) ? "true" : "false";
s += ",\"link_ap\":";
s += apEhLink ? "true" : "false";
s += ",\"anticolisao\":";
s += anticolisao ? "true" : "false";
s += ",\"lim_frente\":";
s += tetoFrente();
s += ",\"bloqueado\":";
s += (moving && requestedDir == DIR_FRENTE && tetoFrente() == 0) ? "true" : "false";
s += ",\"obst_m\":";
s += obstaculoValido() ? String(obstDist, 2) : "null";
s += ",\"livre\":\"";
s += obstaculoValido() ? obstLivre : "";
s += "\",\"visao_ms\":";
s += obstRecebido ? String(millis() - obstRecebidoMs) : "null";
s += ",\"cam_ip\":\"";
s += camIp;
s += "\",\"cam_s\":";
s += camVista ? String((millis() - camVistoMs) / 1000) : "null";
s += "}";
return s;
}
@@ -276,6 +331,24 @@ void handleStatus() {
responder(200, "application/json", statusJson());
}
void handleObstaculo() {
long lim = hasArgv("lim") ? argv("lim").toInt() : 0;
long ttl = hasArgv("ttl") ? argv("ttl").toInt() : 1000;
limFrente = constrain(lim, 0L, (long)MAX_SPEED);
obstAteMs = millis() + constrain(ttl, 0L, (long)MAX_TTL_MS);
obstRecebidoMs = millis();
obstRecebido = true;
obstDist = hasArgv("d") ? argv("d").toFloat() : -1;
obstLivre = argv("livre");
if (obstLivre != "esquerda" && obstLivre != "direita") obstLivre = "";
responder(200, "application/json", statusJson());
}
void handleAnticolisao() {
anticolisao = argv("on") != "0";
responder(200, "application/json", statusJson());
}
void saveNetworks() {
prefs.putInt("count", networkCount);
for (int i = 0; i < MAX_NETWORKS; i++) {
@@ -350,6 +423,27 @@ void startOta() {
otaReady = true;
}
void stopAp() {
if (!apOn) return;
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_STA);
apOn = false;
apEhLink = false;
}
// Rede temporaria para a ESP32-CAM buscar e trocar as redes conhecidas.
void startLinkAp() {
linkAteMs = millis() + LINK_JANELA_MS;
if (apOn && apEhLink) return;
stopAp();
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(LINK_SSID, LINK_SENHA);
apOn = true;
apEhLink = true;
Serial.print("Rede de link com a camera: ");
Serial.println(LINK_SSID);
}
void startSetupAp() {
if (apOn) return;
WiFi.mode(WIFI_AP_STA);
@@ -364,16 +458,18 @@ void startSetupAp() {
}
void stopSetupAp() {
if (!apOn) return;
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_STA);
apOn = false;
if (apOn && !apEhLink) stopAp();
}
// Conecta sem bloquear, para a API e os motores continuarem respondendo.
void updateWifi() {
unsigned long now = millis();
if (apEhLink && (long)(now - linkAteMs) >= 0 && WiFi.softAPgetStationNum() == 0) {
stopAp();
Serial.println("Rede de link fechada");
}
if (WiFi.status() == WL_CONNECTED) {
if (!wasConnected) {
wasConnected = true;
@@ -426,6 +522,59 @@ void updateWifi() {
attemptStartMs = now;
}
// Junta uma rede vinda da camera. Nao troca a senha de uma rede que o robo ja conhece.
bool adicionarRede(const String &ssid, const String &senha) {
if (ssid.length() < 1 || ssid.length() > 32 || senha.length() > 63) return false;
for (int i = 0; i < networkCount; i++) {
if (savedSsid[i] == ssid) return false;
}
if (networkCount >= MAX_NETWORKS) return false;
savedSsid[networkCount] = ssid;
savedPass[networkCount] = senha;
networkCount++;
return true;
}
// Troca de redes com a ESP32-CAM (so pela rede local: devolve senhas).
void handleLink() {
JsonDocument pedido;
if (deserializeJson(pedido, server.arg("plain")) || strcmp(pedido["chave"] | "", LINK_SENHA) != 0) {
server.send(403, "application/json", "{\"error\":\"chave invalida\"}");
return;
}
bool mudou = false;
for (JsonArray rede : pedido["redes"].as<JsonArray>()) {
if (adicionarRede(rede[0] | "", rede[1] | "")) mudou = true;
}
if (mudou) {
saveNetworks();
if (WiFi.status() != WL_CONNECTED && !attempting) nextAttemptMs = millis() + 2000;
}
camIp = pedido["ip"] | "";
camRssi = pedido["rssi"] | 0;
camVistoMs = millis();
camVista = true;
JsonDocument resposta;
JsonArray redes = resposta["redes"].to<JsonArray>();
for (int i = 0; i < networkCount; i++) {
JsonArray rede = redes.add<JsonArray>();
rede.add(savedSsid[i]);
rede.add(savedPass[i]);
}
bool conectado = WiFi.status() == WL_CONNECTED;
resposta["atual"] = conectado ? WiFi.SSID() : "";
resposta["robo_ip"] = conectado ? WiFi.localIP().toString() : "";
String texto;
serializeJson(resposta, texto);
server.send(200, "application/json", texto);
}
void handleLinkAbrir() {
startLinkAp();
responder(200, "application/json", statusJson());
}
void handleWifiList() {
String s = "{\"networks\":[";
for (int i = 0; i < networkCount; i++) {
@@ -529,6 +678,9 @@ void tratarCanal(uint8_t *dados, size_t tamanho) {
else if (rota == "/wifi" && metodo == "GET") handleWifiList();
else if (rota == "/wifi" && metodo == "POST") handleWifiAdd();
else if (rota == "/wifi" && metodo == "DELETE") handleWifiDelete();
else if (rota == "/obstaculo" && metodo == "POST") handleObstaculo();
else if (rota == "/anticolisao" && metodo == "POST") handleAnticolisao();
else if (rota == "/link/abrir" && metodo == "POST") handleLinkAbrir();
viaCanal = false;
JsonDocument resposta;
@@ -580,7 +732,7 @@ void setup() {
WiFi.mode(WIFI_STA);
WiFi.setSleep(false);
WiFi.setAutoReconnect(false);
if (networkCount == 0) startSetupAp();
startLinkAp();
server.on("/move", HTTP_POST, handleMove);
server.on("/stop", HTTP_POST, handleStop);
@@ -588,6 +740,10 @@ void setup() {
server.on("/wifi", HTTP_GET, handleWifiList);
server.on("/wifi", HTTP_POST, handleWifiAdd);
server.on("/wifi", HTTP_DELETE, handleWifiDelete);
server.on("/obstaculo", HTTP_POST, handleObstaculo);
server.on("/anticolisao", HTTP_POST, handleAnticolisao);
server.on("/link", HTTP_POST, handleLink);
server.on("/link/abrir", HTTP_POST, handleLinkAbrir);
server.onNotFound([]() { sendError(404, "rota nao encontrada"); });
server.begin();
descoberta.begin(PORTA_DESCOBERTA);