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.
This commit is contained in:
1 parent
43fae8237a
commit
23479241d8
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);
|
||||
|
||||
@@ -0,0 +1,490 @@
|
||||
// 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);
|
||||
}
|
||||
+150647
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"additionalFiles": "../..,../..,../..",
|
||||
"compiler.optimization_flags": "-Os",
|
||||
"customBuildProperties": "",
|
||||
"fqbn": "esp32:esp32:esp32cam:PartitionScheme=min_spiffs",
|
||||
"hardwareFolders": "/home/marcel/.arduino15/packages/esp32/hardware/esp32/3.3.12,/home/marcel/.arduino15/packages/esp32/hardware/esp32/3.3.12",
|
||||
"otherLibrariesFolders": "/home/marcel/Arduino/libraries",
|
||||
"sketchLocation": "/home/marcel/Documentos/Projeto/Robotica/RoboMovel/software/firmware/RoboMovel_ESP32CAM"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
--flash-mode dio --flash-freq 80m --flash-size 4MB
|
||||
0x1000 RoboMovel_ESP32CAM.ino.bootloader.bin
|
||||
0x8000 RoboMovel_ESP32CAM.ino.partitions.bin
|
||||
0xe000 boot_app0.bin
|
||||
0x10000 RoboMovel_ESP32CAM.ino.bin
|
||||
@@ -0,0 +1,7 @@
|
||||
# Name, Type, SubType, Offset, Size, Flags
|
||||
nvs, data, nvs, 0x9000, 0x5000,
|
||||
otadata, data, ota, 0xe000, 0x2000,
|
||||
app0, app, ota_0, 0x10000, 0x1E0000,
|
||||
app1, app, ota_1, 0x1F0000,0x1E0000,
|
||||
spiffs, data, spiffs, 0x3D0000,0x20000,
|
||||
coredump, data, coredump,0x3F0000,0x10000,
|
||||
|
File diff suppressed because it is too large.
Load diff
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# Compila e grava a ESP32-CAM pelo Wi-Fi. Uso: ./ota.sh [ip_ou_host]
|
||||
# Primeira vez pelo USB (ESP32-CAM-MB): ./ota.sh --usb /dev/ttyUSB0
|
||||
set -e
|
||||
DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CLI=/home/marcel/Applications/arduino-ide-2.3.10/resources/app/lib/backend/resources/arduino-cli
|
||||
FQBN=esp32:esp32:esp32cam:PartitionScheme=min_spiffs
|
||||
BUILD=$(mktemp -d)
|
||||
trap 'rm -rf "$BUILD"' EXIT
|
||||
"$CLI" compile --fqbn "$FQBN" --output-dir "$BUILD" "$DIR"
|
||||
if [ "$1" = "--usb" ]; then
|
||||
"$CLI" upload --fqbn "$FQBN" -p "${2:-/dev/ttyUSB0}" --input-dir "$BUILD" "$DIR"
|
||||
exit
|
||||
fi
|
||||
HOST="${1:-robomovel-cam.local}"
|
||||
ESPOTA=$(ls ~/.arduino15/packages/esp32/hardware/esp32/*/tools/espota.py | tail -1)
|
||||
python3 "$ESPOTA" -i "$(getent ahostsv4 "$HOST" | awk '{print $1; exit}')" -f "$BUILD/$(basename "$DIR").ino.bin"
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copie para redes_padrao.h e troque pelos SSIDs e senhas reais (na ordem de tentativa).
|
||||
const char *DEFAULT_NETWORKS[][2] = {
|
||||
{"MINHA_REDE", "minha_senha"},
|
||||
};
|
||||
Reference in new issue
Block a user