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
@@ -158,3 +158,7 @@ temp/
|
|||||||
*.key
|
*.key
|
||||||
secrets.json
|
secrets.json
|
||||||
credentials.json
|
credentials.json
|
||||||
|
|
||||||
|
# Segredos dos firmwares
|
||||||
|
redes_padrao.h
|
||||||
|
link_senha.h
|
||||||
@@ -15,7 +15,7 @@ source.include_exts = py,png,jpg,jpeg,kv,atlas,json
|
|||||||
source.exclude_dirs = .venv,.buildozer-venv,__pycache__,bin,.git
|
source.exclude_dirs = .venv,.buildozer-venv,__pycache__,bin,.git
|
||||||
|
|
||||||
# (str) Versão mostrada no Android
|
# (str) Versão mostrada no Android
|
||||||
version = 0.1.0
|
version = 0.2.0
|
||||||
|
|
||||||
# (list) Dependências Python empacotadas no APK
|
# (list) Dependências Python empacotadas no APK
|
||||||
requirements = python3,kivy==2.3.1,pyjnius,certifi
|
requirements = python3,kivy==2.3.1,pyjnius,certifi
|
||||||
|
|||||||
@@ -14,7 +14,13 @@ Procura sozinho quando o robô salvo para de responder, ou pelo botão "Procurar
|
|||||||
|
|
||||||
Pela internet: escreva "pipe.ovelha.cloud" no campo Robô, ou deixe o app usar quando não achar
|
Pela internet: escreva "pipe.ovelha.cloud" no campo Robô, ou deixe o app usar quando não achar
|
||||||
o robô na rede local. Os comandos vão por https://pipe.ovelha.cloud/c/robomovel/<rota>.
|
o robô na rede local. Os comandos vão por https://pipe.ovelha.cloud/c/robomovel/<rota>.
|
||||||
|
|
||||||
|
Anticolisão: a ESP32-CAM manda quadros para o serviço visao.py na VPS (Depth Anything V2 métrico),
|
||||||
|
que limita a velocidade para frente no próprio robô (bloqueia abaixo de ~0,45 m). O app mostra a
|
||||||
|
câmera ou o mapa de profundidade (toque na imagem para alternar), as distâncias, e liga/desliga
|
||||||
|
a anticolisão. "Parear câmera" reabre por 3 min a rede RoboMovel-Link para a câmera trocar redes.
|
||||||
"""
|
"""
|
||||||
|
import io
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import socket
|
import socket
|
||||||
@@ -36,11 +42,13 @@ if platform not in ("android", "ios"):
|
|||||||
|
|
||||||
from kivy.app import App
|
from kivy.app import App
|
||||||
from kivy.clock import Clock, mainthread
|
from kivy.clock import Clock, mainthread
|
||||||
|
from kivy.core.image import Image as CoreImage
|
||||||
from kivy.core.window import Window
|
from kivy.core.window import Window
|
||||||
from kivy.graphics import Color, Ellipse, Line
|
from kivy.graphics import Color, Ellipse, Line
|
||||||
from kivy.metrics import dp, sp
|
from kivy.metrics import dp, sp
|
||||||
from kivy.uix.boxlayout import BoxLayout
|
from kivy.uix.boxlayout import BoxLayout
|
||||||
from kivy.uix.button import Button
|
from kivy.uix.button import Button
|
||||||
|
from kivy.uix.image import Image
|
||||||
from kivy.uix.label import Label
|
from kivy.uix.label import Label
|
||||||
from kivy.uix.slider import Slider
|
from kivy.uix.slider import Slider
|
||||||
from kivy.uix.textinput import TextInput
|
from kivy.uix.textinput import TextInput
|
||||||
@@ -57,6 +65,8 @@ PORTA_DESCOBERTA = 4210
|
|||||||
FALHAS_PARA_PROCURAR = 3
|
FALHAS_PARA_PROCURAR = 3
|
||||||
PIPE_HOST = "pipe.ovelha.cloud"
|
PIPE_HOST = "pipe.ovelha.cloud"
|
||||||
PIPE_CANAL = "robomovel"
|
PIPE_CANAL = "robomovel"
|
||||||
|
VISAO_URL = f"https://{PIPE_HOST}/c/robomovel-visao"
|
||||||
|
VISAO_IMAGEM_S = 0.35
|
||||||
|
|
||||||
|
|
||||||
def contexto_ssl():
|
def contexto_ssl():
|
||||||
@@ -199,6 +209,25 @@ def comando_dos_joysticks(mover, girar, vel_max):
|
|||||||
return direcao, int(VEL_MIN + fracao * (vel_max - VEL_MIN))
|
return direcao, int(VEL_MIN + fracao * (vel_max - VEL_MIN))
|
||||||
|
|
||||||
|
|
||||||
|
class ImagemToque(Image):
|
||||||
|
"""Imagem que chama ao_tocar quando recebe um toque."""
|
||||||
|
|
||||||
|
def __init__(self, ao_tocar, **kw):
|
||||||
|
super().__init__(**kw)
|
||||||
|
self.ao_tocar = ao_tocar
|
||||||
|
|
||||||
|
def on_touch_down(self, toque):
|
||||||
|
if self.collide_point(*toque.pos):
|
||||||
|
self.ao_tocar()
|
||||||
|
return True
|
||||||
|
return super().on_touch_down(toque)
|
||||||
|
|
||||||
|
|
||||||
|
def baixar(url, timeout=5):
|
||||||
|
with urllib.request.urlopen(url, timeout=timeout, context=SSL_CONTEXTO) as r:
|
||||||
|
return r.read()
|
||||||
|
|
||||||
|
|
||||||
class Painel(BoxLayout):
|
class Painel(BoxLayout):
|
||||||
def __init__(self, **kw):
|
def __init__(self, **kw):
|
||||||
super().__init__(orientation="vertical", padding=dp(12), spacing=dp(10), **kw)
|
super().__init__(orientation="vertical", padding=dp(12), spacing=dp(10), **kw)
|
||||||
@@ -226,6 +255,27 @@ class Painel(BoxLayout):
|
|||||||
linha_host.add_widget(b_procurar)
|
linha_host.add_widget(b_procurar)
|
||||||
self.add_widget(linha_host)
|
self.add_widget(linha_host)
|
||||||
|
|
||||||
|
# Visão: imagem (toque alterna câmera/profundidade) + distâncias e botões
|
||||||
|
linha_visao = BoxLayout(size_hint_y=None, height=dp(170), spacing=dp(8))
|
||||||
|
self.tipo_imagem = "prof"
|
||||||
|
self.imagem = ImagemToque(self._alternar_imagem, size_hint_x=0.42, fit_mode="contain")
|
||||||
|
linha_visao.add_widget(self.imagem)
|
||||||
|
coluna = BoxLayout(orientation="vertical", spacing=dp(6))
|
||||||
|
self.lbl_visao = Label(text="visão: aguardando…", font_size=sp(13), halign="left", valign="middle")
|
||||||
|
self.lbl_visao.bind(size=lambda l, s: setattr(l, "text_size", s))
|
||||||
|
coluna.add_widget(self.lbl_visao)
|
||||||
|
self.b_anticolisao = Button(text="Anticolisão: ?", size_hint_y=None, height=dp(40), font_size=sp(14),
|
||||||
|
background_color=(0.25, 0.5, 0.75, 1))
|
||||||
|
self.b_anticolisao.bind(on_release=lambda *_: self._alternar_anticolisao())
|
||||||
|
coluna.add_widget(self.b_anticolisao)
|
||||||
|
b_parear = Button(text="Parear câmera", size_hint_y=None, height=dp(40), font_size=sp(14),
|
||||||
|
background_color=(0.35, 0.35, 0.45, 1))
|
||||||
|
b_parear.bind(on_release=lambda *_: self._parear_camera())
|
||||||
|
coluna.add_widget(b_parear)
|
||||||
|
linha_visao.add_widget(coluna)
|
||||||
|
self.add_widget(linha_visao)
|
||||||
|
self._anticolisao = None
|
||||||
|
|
||||||
self.lbl_vel = Label(size_hint_y=None, height=dp(24), font_size=sp(14))
|
self.lbl_vel = Label(size_hint_y=None, height=dp(24), font_size=sp(14))
|
||||||
self.add_widget(self.lbl_vel)
|
self.add_widget(self.lbl_vel)
|
||||||
self.slider = Slider(min=VEL_MIN, max=VEL_MAX, step=50, value=self.vel_max,
|
self.slider = Slider(min=VEL_MIN, max=VEL_MAX, step=50, value=self.vel_max,
|
||||||
@@ -259,6 +309,8 @@ class Painel(BoxLayout):
|
|||||||
self._proxima_procura = 0
|
self._proxima_procura = 0
|
||||||
threading.Thread(target=self._laco_envio, daemon=True).start()
|
threading.Thread(target=self._laco_envio, daemon=True).start()
|
||||||
threading.Thread(target=self._laco_status, daemon=True).start()
|
threading.Thread(target=self._laco_status, daemon=True).start()
|
||||||
|
threading.Thread(target=self._laco_visao_estado, daemon=True).start()
|
||||||
|
threading.Thread(target=self._laco_visao_imagem, daemon=True).start()
|
||||||
Clock.schedule_interval(self._ler_joysticks, 1 / 30)
|
Clock.schedule_interval(self._ler_joysticks, 1 / 30)
|
||||||
|
|
||||||
# ------------------------------------------------------------ configuração
|
# ------------------------------------------------------------ configuração
|
||||||
@@ -337,6 +389,70 @@ class Painel(BoxLayout):
|
|||||||
if salvar:
|
if salvar:
|
||||||
self._salvar_config()
|
self._salvar_config()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------ visão / anticolisão
|
||||||
|
def _alternar_imagem(self):
|
||||||
|
self.tipo_imagem = "foto" if self.tipo_imagem == "prof" else "prof"
|
||||||
|
|
||||||
|
def _alternar_anticolisao(self):
|
||||||
|
novo = "0" if self._anticolisao else "1"
|
||||||
|
threading.Thread(target=self._comando_simples, args=("/anticolisao", {"on": novo}),
|
||||||
|
daemon=True).start()
|
||||||
|
|
||||||
|
def _parear_camera(self):
|
||||||
|
threading.Thread(target=self._comando_simples, args=("/link/abrir", None), daemon=True).start()
|
||||||
|
self._mostrar("rede RoboMovel-Link aberta por 3 min: a câmera troca as redes ao entrar nela")
|
||||||
|
|
||||||
|
def _comando_simples(self, rota, params):
|
||||||
|
try:
|
||||||
|
self._mostrar_anticolisao(self._http("POST", rota, params).get("anticolisao"))
|
||||||
|
except Exception as erro:
|
||||||
|
self._mostrar(f"sem resposta do robô ({self.host}): {erro}")
|
||||||
|
|
||||||
|
@mainthread
|
||||||
|
def _mostrar_anticolisao(self, ligada):
|
||||||
|
if ligada is None:
|
||||||
|
return
|
||||||
|
self._anticolisao = ligada
|
||||||
|
self.b_anticolisao.text = "Anticolisão: " + ("LIGADA" if ligada else "desligada")
|
||||||
|
self.b_anticolisao.background_color = (0.2, 0.6, 0.3, 1) if ligada else (0.6, 0.35, 0.2, 1)
|
||||||
|
|
||||||
|
def _laco_visao_estado(self):
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
e = json.loads(baixar(VISAO_URL + "/estado"))
|
||||||
|
if e.get("ativo"):
|
||||||
|
lim = e.get("lim", 0)
|
||||||
|
aviso = "BLOQUEADO" if lim == 0 else ("livre" if lim >= VEL_MAX else f"até {lim} passos/s")
|
||||||
|
texto = (f"frente: {aviso}\n"
|
||||||
|
f"esq {e.get('esq_m')} · centro {e.get('centro_m')} · dir {e.get('dir_m')} m\n"
|
||||||
|
f"mais livre: {e.get('livre')} · {e.get('ms')} ms/quadro")
|
||||||
|
else:
|
||||||
|
texto = "visão parada: " + str(e.get("erro") or "sem câmera")
|
||||||
|
except Exception as erro:
|
||||||
|
texto = f"visão indisponível: {erro}"
|
||||||
|
self._mostrar_visao(texto)
|
||||||
|
threading.Event().wait(0.7)
|
||||||
|
|
||||||
|
def _laco_visao_imagem(self):
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
dados = baixar(f"{VISAO_URL}/imagem.jpg?tipo={self.tipo_imagem}")
|
||||||
|
self._mostrar_imagem(dados)
|
||||||
|
except Exception:
|
||||||
|
threading.Event().wait(1.5)
|
||||||
|
threading.Event().wait(VISAO_IMAGEM_S)
|
||||||
|
|
||||||
|
@mainthread
|
||||||
|
def _mostrar_visao(self, texto):
|
||||||
|
self.lbl_visao.text = texto
|
||||||
|
|
||||||
|
@mainthread
|
||||||
|
def _mostrar_imagem(self, dados):
|
||||||
|
try:
|
||||||
|
self.imagem.texture = CoreImage(io.BytesIO(dados), ext="jpg").texture
|
||||||
|
except Exception as erro:
|
||||||
|
print("imagem inválida:", erro)
|
||||||
|
|
||||||
# ------------------------------------------------------------ comandos
|
# ------------------------------------------------------------ comandos
|
||||||
def _ler_joysticks(self, _dt):
|
def _ler_joysticks(self, _dt):
|
||||||
novo = comando_dos_joysticks(self.mover.valor, self.girar.valor, self.vel_max)
|
novo = comando_dos_joysticks(self.mover.valor, self.girar.valor, self.vel_max)
|
||||||
@@ -385,10 +501,13 @@ class Painel(BoxLayout):
|
|||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
d = self._http("GET", "/status")
|
d = self._http("GET", "/status")
|
||||||
if d.get("moving"):
|
if d.get("bloqueado"):
|
||||||
|
texto = f"OBSTÁCULO a {d.get('obst_m')} m: frente bloqueada (livre à {d.get('livre') or '?'})"
|
||||||
|
elif d.get("moving"):
|
||||||
texto = f"Movendo: {d.get('dir')} · {d.get('speed')} passos/s"
|
texto = f"Movendo: {d.get('dir')} · {d.get('speed')} passos/s"
|
||||||
else:
|
else:
|
||||||
texto = "Parado"
|
texto = "Parado"
|
||||||
|
self._mostrar_anticolisao(d.get("anticolisao"))
|
||||||
texto += f"\n{self.host} · rede {d.get('ssid') or '-'} · fw {d.get('fw', '?')}"
|
texto += f"\n{self.host} · rede {d.get('ssid') or '-'} · fw {d.get('fw', '?')}"
|
||||||
self._falhas = 0
|
self._falhas = 0
|
||||||
if not self._procurando:
|
if not self._procurando:
|
||||||
|
|||||||
@@ -14,6 +14,14 @@
|
|||||||
// DELETE /wifi?ssid=NOME
|
// DELETE /wifi?ssid=NOME
|
||||||
// Canal publico: conecta em wss://pipe.ovelha.cloud/ws/robomovel e aceita a mesma API por
|
// 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.
|
// 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.
|
// 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).
|
// Atualizacao pela rede (OTA): host robomovel, sem senha (use ./ota.sh).
|
||||||
// Os motores param no inicio da gravacao.
|
// Os motores param no inicio da gravacao.
|
||||||
@@ -39,6 +47,7 @@
|
|||||||
#include <WebSocketsClient.h>
|
#include <WebSocketsClient.h>
|
||||||
#include <ArduinoJson.h>
|
#include <ArduinoJson.h>
|
||||||
#include "soc/gpio_reg.h"
|
#include "soc/gpio_reg.h"
|
||||||
|
#include "link_senha.h"
|
||||||
|
|
||||||
enum Wheel { FL, FR, RL, RR, WHEELS };
|
enum Wheel { FL, FR, RL, RR, WHEELS };
|
||||||
|
|
||||||
@@ -85,7 +94,7 @@ unsigned long lastRampMs = 0;
|
|||||||
|
|
||||||
// ---- Wi-Fi ----
|
// ---- Wi-Fi ----
|
||||||
const int MAX_NETWORKS = 5;
|
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).
|
// 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.
|
// Copie redes_padrao.exemplo.h para redes_padrao.h e preencha. Sao recadastradas a cada boot.
|
||||||
#include "redes_padrao.h"
|
#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 ATTEMPT_MS = 12000; // tempo para tentar cada rede
|
||||||
const unsigned long RETRY_MS = 30000; // espera apos falhar em todas
|
const unsigned long RETRY_MS = 30000; // espera apos falhar em todas
|
||||||
const unsigned long AP_GRACE_MS = 5000; // mantem o AP apos conectar
|
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;
|
Preferences prefs;
|
||||||
String savedSsid[MAX_NETWORKS];
|
String savedSsid[MAX_NETWORKS];
|
||||||
@@ -104,6 +115,23 @@ WiFiUDP descoberta;
|
|||||||
WebSocketsClient canal; // canal publico pipe.ovelha.cloud
|
WebSocketsClient canal; // canal publico pipe.ovelha.cloud
|
||||||
const uint16_t PORTA_DESCOBERTA = 4210;
|
const uint16_t PORTA_DESCOBERTA = 4210;
|
||||||
bool apOn = false;
|
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 wasConnected = false;
|
||||||
bool attempting = false;
|
bool attempting = false;
|
||||||
bool forceAttempt = false;
|
bool forceAttempt = false;
|
||||||
@@ -140,6 +168,14 @@ void applyDirection(int d) {
|
|||||||
appliedDir = d;
|
appliedDir = d;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool obstaculoValido() {
|
||||||
|
return anticolisao && obstRecebido && (long)(millis() - obstAteMs) < 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t tetoFrente() {
|
||||||
|
return obstaculoValido() ? limFrente : MAX_SPEED;
|
||||||
|
}
|
||||||
|
|
||||||
void requestStop() {
|
void requestStop() {
|
||||||
moving = false;
|
moving = false;
|
||||||
targetSpeed = 0;
|
targetSpeed = 0;
|
||||||
@@ -156,6 +192,7 @@ void updateMotion() {
|
|||||||
if (moving && moveViaSta && WiFi.status() != WL_CONNECTED) requestStop();
|
if (moving && moveViaSta && WiFi.status() != WL_CONNECTED) requestStop();
|
||||||
|
|
||||||
float desired = targetSpeed;
|
float desired = targetSpeed;
|
||||||
|
if (moving && requestedDir == DIR_FRENTE) desired = min(desired, (float)tetoFrente());
|
||||||
if (moving && requestedDir != appliedDir) {
|
if (moving && requestedDir != appliedDir) {
|
||||||
if (currentSpeed <= 0) applyDirection(requestedDir);
|
if (currentSpeed <= 0) applyDirection(requestedDir);
|
||||||
else desired = 0;
|
else desired = 0;
|
||||||
@@ -206,7 +243,25 @@ String statusJson() {
|
|||||||
s += "\",\"canal\":";
|
s += "\",\"canal\":";
|
||||||
s += canal.isConnected() ? "true" : "false";
|
s += canal.isConnected() ? "true" : "false";
|
||||||
s += ",\"setup_ap\":";
|
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 += "}";
|
s += "}";
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
@@ -276,6 +331,24 @@ void handleStatus() {
|
|||||||
responder(200, "application/json", statusJson());
|
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() {
|
void saveNetworks() {
|
||||||
prefs.putInt("count", networkCount);
|
prefs.putInt("count", networkCount);
|
||||||
for (int i = 0; i < MAX_NETWORKS; i++) {
|
for (int i = 0; i < MAX_NETWORKS; i++) {
|
||||||
@@ -350,6 +423,27 @@ void startOta() {
|
|||||||
otaReady = true;
|
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() {
|
void startSetupAp() {
|
||||||
if (apOn) return;
|
if (apOn) return;
|
||||||
WiFi.mode(WIFI_AP_STA);
|
WiFi.mode(WIFI_AP_STA);
|
||||||
@@ -364,16 +458,18 @@ void startSetupAp() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void stopSetupAp() {
|
void stopSetupAp() {
|
||||||
if (!apOn) return;
|
if (apOn && !apEhLink) stopAp();
|
||||||
WiFi.softAPdisconnect(true);
|
|
||||||
WiFi.mode(WIFI_STA);
|
|
||||||
apOn = false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Conecta sem bloquear, para a API e os motores continuarem respondendo.
|
// Conecta sem bloquear, para a API e os motores continuarem respondendo.
|
||||||
void updateWifi() {
|
void updateWifi() {
|
||||||
unsigned long now = millis();
|
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 (WiFi.status() == WL_CONNECTED) {
|
||||||
if (!wasConnected) {
|
if (!wasConnected) {
|
||||||
wasConnected = true;
|
wasConnected = true;
|
||||||
@@ -426,6 +522,59 @@ void updateWifi() {
|
|||||||
attemptStartMs = now;
|
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() {
|
void handleWifiList() {
|
||||||
String s = "{\"networks\":[";
|
String s = "{\"networks\":[";
|
||||||
for (int i = 0; i < networkCount; i++) {
|
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 == "GET") handleWifiList();
|
||||||
else if (rota == "/wifi" && metodo == "POST") handleWifiAdd();
|
else if (rota == "/wifi" && metodo == "POST") handleWifiAdd();
|
||||||
else if (rota == "/wifi" && metodo == "DELETE") handleWifiDelete();
|
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;
|
viaCanal = false;
|
||||||
|
|
||||||
JsonDocument resposta;
|
JsonDocument resposta;
|
||||||
@@ -580,7 +732,7 @@ void setup() {
|
|||||||
WiFi.mode(WIFI_STA);
|
WiFi.mode(WIFI_STA);
|
||||||
WiFi.setSleep(false);
|
WiFi.setSleep(false);
|
||||||
WiFi.setAutoReconnect(false);
|
WiFi.setAutoReconnect(false);
|
||||||
if (networkCount == 0) startSetupAp();
|
startLinkAp();
|
||||||
|
|
||||||
server.on("/move", HTTP_POST, handleMove);
|
server.on("/move", HTTP_POST, handleMove);
|
||||||
server.on("/stop", HTTP_POST, handleStop);
|
server.on("/stop", HTTP_POST, handleStop);
|
||||||
@@ -588,6 +740,10 @@ void setup() {
|
|||||||
server.on("/wifi", HTTP_GET, handleWifiList);
|
server.on("/wifi", HTTP_GET, handleWifiList);
|
||||||
server.on("/wifi", HTTP_POST, handleWifiAdd);
|
server.on("/wifi", HTTP_POST, handleWifiAdd);
|
||||||
server.on("/wifi", HTTP_DELETE, handleWifiDelete);
|
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.onNotFound([]() { sendError(404, "rota nao encontrada"); });
|
||||||
server.begin();
|
server.begin();
|
||||||
descoberta.begin(PORTA_DESCOBERTA);
|
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"},
|
||||||
|
};
|
||||||
@@ -4,9 +4,12 @@ WebSocket /ws/<canal> entra no canal. Mensagens de texto vão para os o
|
|||||||
HTTP /c/<canal>/<rota> vira uma requisição para quem está no canal:
|
HTTP /c/<canal>/<rota> vira uma requisição para quem está no canal:
|
||||||
-> {"tipo":"req","id":"...","method":"POST","path":"/move","query":{...}}
|
-> {"tipo":"req","id":"...","method":"POST","path":"/move","query":{...}}
|
||||||
<- {"tipo":"resp","id":"...","status":200,"body":"..."} (o primeiro que responder)
|
<- {"tipo":"resp","id":"...","status":200,"body":"..."} (o primeiro que responder)
|
||||||
|
ou {"tipo":"resp",...,"body_b64":"...","content_type":"image/jpeg"} para conteúdo binário
|
||||||
|
Mensagens binárias no WebSocket (ex.: quadros JPEG da câmera) vão para os outros do canal.
|
||||||
GET /canais lista os canais e quantos estão conectados.
|
GET /canais lista os canais e quantos estão conectados.
|
||||||
"""
|
"""
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import base64
|
||||||
import json
|
import json
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
@@ -25,6 +28,11 @@ async def ws_canal(request):
|
|||||||
membros.add(ws)
|
membros.add(ws)
|
||||||
try:
|
try:
|
||||||
async for msg in ws:
|
async for msg in ws:
|
||||||
|
if msg.type == WSMsgType.BINARY:
|
||||||
|
for outro in list(membros):
|
||||||
|
if outro is not ws and not outro.closed:
|
||||||
|
await outro.send_bytes(msg.data)
|
||||||
|
continue
|
||||||
if msg.type != WSMsgType.TEXT:
|
if msg.type != WSMsgType.TEXT:
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
@@ -67,8 +75,13 @@ async def http_canal(request):
|
|||||||
return web.json_response({"error": "o canal não respondeu a tempo"}, status=504)
|
return web.json_response({"error": "o canal não respondeu a tempo"}, status=504)
|
||||||
finally:
|
finally:
|
||||||
pendentes.pop(pedido["id"], None)
|
pendentes.pop(pedido["id"], None)
|
||||||
return web.Response(text=str(resp.get("body", "")), status=int(resp.get("status", 200)),
|
status = int(resp.get("status", 200))
|
||||||
content_type="application/json")
|
cabecalhos = {"Cache-Control": "no-store", "Access-Control-Allow-Origin": "*"}
|
||||||
|
if "body_b64" in resp:
|
||||||
|
return web.Response(body=base64.b64decode(resp["body_b64"]), status=status, headers=cabecalhos,
|
||||||
|
content_type=resp.get("content_type", "application/octet-stream"))
|
||||||
|
return web.Response(text=str(resp.get("body", "")), status=status, headers=cabecalhos,
|
||||||
|
content_type=resp.get("content_type", "application/json"))
|
||||||
|
|
||||||
|
|
||||||
async def listar(_request):
|
async def listar(_request):
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""Ponte para câmeras sem o firmware novo: busca http://<ip>:81/foto na rede local e entrega no canal
|
||||||
|
robomovel-cam do pipe, do mesmo jeito que o firmware RoboMovel_ESP32CAM faz sozinho.
|
||||||
|
|
||||||
|
python3 ponte_camera_lan.py 192.168.0.75
|
||||||
|
|
||||||
|
Precisa de um PC ligado na mesma rede da câmera. Só depende de aiohttp.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
|
|
||||||
|
CAM = sys.argv[1] if len(sys.argv) > 1 else "192.168.0.75"
|
||||||
|
PIPE_WS = "wss://pipe.ovelha.cloud/ws/robomovel-cam"
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
async with aiohttp.ClientSession() as sessao:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
async with sessao.ws_connect(PIPE_WS, heartbeat=20) as ws:
|
||||||
|
print("ponte conectada; câmera", CAM, flush=True)
|
||||||
|
async for msg in ws:
|
||||||
|
if msg.type == aiohttp.WSMsgType.TEXT and msg.data == "quadro":
|
||||||
|
async with sessao.get(f"http://{CAM}:81/foto",
|
||||||
|
timeout=aiohttp.ClientTimeout(total=3)) as r:
|
||||||
|
await ws.send_bytes(await r.read())
|
||||||
|
except Exception as erro:
|
||||||
|
print("ponte:", erro, flush=True)
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
|
||||||
|
|
||||||
|
asyncio.run(main())
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
aiohttp
|
||||||
|
numpy
|
||||||
|
onnxruntime
|
||||||
|
opencv-python-headless
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
"""Anticolisão do RoboMovel: câmera -> Depth Anything V2 (métrico, indoor) -> limite de velocidade no robô.
|
||||||
|
|
||||||
|
Roda na VPS ao lado do pipe (ws://127.0.0.1:8100):
|
||||||
|
canal robomovel-cam a ESP32-CAM (ou ponte_camera_lan.py) entra aqui. Este serviço pede um quadro
|
||||||
|
com a mensagem de texto "quadro" e a câmera responde com o JPEG em binário.
|
||||||
|
Pede o próximo assim que recebe um, então nunca acumula fila.
|
||||||
|
canal robomovel o robô. A cada quadro: POST /obstaculo?lim=<passos/s>&ttl=<ms>&d=<m>&livre=<lado>
|
||||||
|
lim é o teto de velocidade para "frente" (0 = bloqueado). Se este serviço parar,
|
||||||
|
o teto expira em TTL_MS e o robô volta ao normal.
|
||||||
|
canal robomovel-visao para o app: GET /estado (JSON), GET /imagem.jpg?tipo=prof|foto
|
||||||
|
|
||||||
|
Variáveis de ambiente (valores padrão entre parênteses):
|
||||||
|
ROTACAO (90) rotação da imagem da câmera em graus no sentido horário (0, 90, 180, 270)
|
||||||
|
PARAR_M (0.45) distância em metros em que "frente" fica bloqueado
|
||||||
|
LIVRE_M (1.00) distância a partir da qual não há limite
|
||||||
|
FAIXA (0.10,0.62) faixa vertical da imagem analisada (fração da altura); o chão fica abaixo dela
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import pathlib
|
||||||
|
import time
|
||||||
|
|
||||||
|
import aiohttp
|
||||||
|
import cv2
|
||||||
|
import numpy as np
|
||||||
|
import onnxruntime as ort
|
||||||
|
|
||||||
|
PIPE = os.environ.get("PIPE", "http://127.0.0.1:8100")
|
||||||
|
MODELO = pathlib.Path(__file__).resolve().parent / "modelos" / "depth_anything_v2_metric_indoor_small.onnx"
|
||||||
|
LADO = 266
|
||||||
|
MEDIA = np.array([0.485, 0.456, 0.406], np.float32)
|
||||||
|
DESVIO = np.array([0.229, 0.224, 0.225], np.float32)
|
||||||
|
ROTACOES = {0: None, 90: cv2.ROTATE_90_CLOCKWISE, 180: cv2.ROTATE_180, 270: cv2.ROTATE_90_COUNTERCLOCKWISE}
|
||||||
|
|
||||||
|
ROTACAO = ROTACOES[int(os.environ.get("ROTACAO", "90"))]
|
||||||
|
PARAR_M = float(os.environ.get("PARAR_M", "0.45"))
|
||||||
|
LIVRE_M = float(os.environ.get("LIVRE_M", "1.00"))
|
||||||
|
FAIXA = tuple(float(v) for v in os.environ.get("FAIXA", "0.10,0.62").split(","))
|
||||||
|
VEL_MIN, VEL_MAX = 100, 1000 # limites do firmware (passos/s)
|
||||||
|
TTL_MS = 1500
|
||||||
|
ESPERA_QUADRO_S = 6.0
|
||||||
|
|
||||||
|
|
||||||
|
class Profundidade:
|
||||||
|
def __init__(self):
|
||||||
|
opcoes = ort.SessionOptions()
|
||||||
|
opcoes.intra_op_num_threads = int(os.environ.get("THREADS", "2"))
|
||||||
|
self.sessao = ort.InferenceSession(str(MODELO), opcoes, providers=["CPUExecutionProvider"])
|
||||||
|
self.entrada = self.sessao.get_inputs()[0].name
|
||||||
|
|
||||||
|
def metros(self, bgr):
|
||||||
|
"""Imagem BGR -> profundidade em metros, LADO x LADO."""
|
||||||
|
rgb = cv2.cvtColor(cv2.resize(bgr, (LADO, LADO), interpolation=cv2.INTER_AREA), cv2.COLOR_BGR2RGB)
|
||||||
|
x = ((rgb.astype(np.float32) / 255.0 - MEDIA) / DESVIO).transpose(2, 0, 1)[None]
|
||||||
|
return self.sessao.run(None, {self.entrada: x})[0][0]
|
||||||
|
|
||||||
|
|
||||||
|
def analisar(m):
|
||||||
|
"""Distância (m) dos obstáculos à esquerda, no centro e à direita, dentro da FAIXA vertical."""
|
||||||
|
a, b = int(FAIXA[0] * LADO), int(FAIXA[1] * LADO)
|
||||||
|
faixa = m[a:b]
|
||||||
|
terco = LADO // 3
|
||||||
|
zonas = [faixa[:, :terco], faixa[:, terco:2 * terco], faixa[:, 2 * terco:]]
|
||||||
|
esq, centro, dir_ = (float(np.percentile(z, 5)) for z in zonas)
|
||||||
|
return esq, centro, dir_
|
||||||
|
|
||||||
|
|
||||||
|
def limite(esq, centro, dir_):
|
||||||
|
"""Teto de velocidade para frente: o centro pesa inteiro, as laterais com folga de 15 cm."""
|
||||||
|
d = min(centro, esq + 0.15, dir_ + 0.15)
|
||||||
|
if d <= PARAR_M:
|
||||||
|
return d, 0
|
||||||
|
if d >= LIVRE_M:
|
||||||
|
return d, VEL_MAX
|
||||||
|
fracao = (d - PARAR_M) / (LIVRE_M - PARAR_M)
|
||||||
|
return d, int(VEL_MIN + fracao * (VEL_MAX - VEL_MIN))
|
||||||
|
|
||||||
|
|
||||||
|
def colorir(m, forma):
|
||||||
|
"""Metros -> imagem TURBO (vermelho = perto, azul = longe; 0,3 a 2 m), branco abaixo de PARAR_M."""
|
||||||
|
inv = np.clip(1.0 - (m - 0.3) / 1.7, 0, 1)
|
||||||
|
cor = cv2.applyColorMap((inv * 255).astype(np.uint8), cv2.COLORMAP_TURBO)
|
||||||
|
cor[m < PARAR_M] = (255, 255, 255)
|
||||||
|
cor = cv2.resize(cor, (forma[1], forma[0]), interpolation=cv2.INTER_LINEAR)
|
||||||
|
h, w = forma[:2]
|
||||||
|
for f in FAIXA:
|
||||||
|
cv2.line(cor, (0, int(f * h)), (w, int(f * h)), (255, 255, 255), 1)
|
||||||
|
for k in (1, 2):
|
||||||
|
cv2.line(cor, (k * w // 3, int(FAIXA[0] * h)), (k * w // 3, int(FAIXA[1] * h)), (255, 255, 255), 1)
|
||||||
|
return cor
|
||||||
|
|
||||||
|
|
||||||
|
class Visao:
|
||||||
|
def __init__(self):
|
||||||
|
self.prof = Profundidade()
|
||||||
|
self.estado = {"ativo": False}
|
||||||
|
self.foto = b""
|
||||||
|
self.imagem_prof = b""
|
||||||
|
self.envio_robo = None
|
||||||
|
|
||||||
|
async def rodar(self):
|
||||||
|
async with aiohttp.ClientSession() as sessao:
|
||||||
|
self.sessao = sessao
|
||||||
|
await asyncio.gather(self._laco_camera(), self._laco_app())
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- câmera -> profundidade -> robô
|
||||||
|
async def _laco_camera(self):
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
async with self.sessao.ws_connect(PIPE + "/ws/robomovel-cam", heartbeat=20) as ws:
|
||||||
|
print("canal da câmera conectado", flush=True)
|
||||||
|
while True:
|
||||||
|
await ws.send_str("quadro")
|
||||||
|
jpeg = await self._esperar_quadro(ws)
|
||||||
|
if jpeg is None:
|
||||||
|
self.estado = {"ativo": False, "erro": "câmera não mandou quadro"}
|
||||||
|
await asyncio.sleep(1)
|
||||||
|
continue
|
||||||
|
await self._processar(jpeg)
|
||||||
|
except Exception as erro:
|
||||||
|
self.estado = {"ativo": False, "erro": str(erro)}
|
||||||
|
print("canal da câmera:", erro, flush=True)
|
||||||
|
await asyncio.sleep(3)
|
||||||
|
|
||||||
|
async def _esperar_quadro(self, ws):
|
||||||
|
fim = time.monotonic() + ESPERA_QUADRO_S
|
||||||
|
while (resta := fim - time.monotonic()) > 0:
|
||||||
|
try:
|
||||||
|
msg = await ws.receive(timeout=resta)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
return None
|
||||||
|
if msg.type == aiohttp.WSMsgType.BINARY:
|
||||||
|
return msg.data
|
||||||
|
if msg.type in (aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR):
|
||||||
|
raise ConnectionError("canal da câmera fechou")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _processar(self, jpeg):
|
||||||
|
img = cv2.imdecode(np.frombuffer(jpeg, np.uint8), cv2.IMREAD_COLOR)
|
||||||
|
if img is None:
|
||||||
|
return
|
||||||
|
if ROTACAO is not None:
|
||||||
|
img = cv2.rotate(img, ROTACAO)
|
||||||
|
t0 = time.perf_counter()
|
||||||
|
m = await asyncio.to_thread(self.prof.metros, img)
|
||||||
|
ms = (time.perf_counter() - t0) * 1000
|
||||||
|
esq, centro, dir_ = analisar(m)
|
||||||
|
d, lim = limite(esq, centro, dir_)
|
||||||
|
livre = "esquerda" if esq > dir_ else "direita"
|
||||||
|
agora = time.time()
|
||||||
|
fps = 1.0 / max(agora - self.estado.get("t", 0), 1e-3) if self.estado.get("ativo") else 0.0
|
||||||
|
self.estado = {"ativo": True, "t": agora, "fps": round(fps, 1), "ms": round(ms),
|
||||||
|
"esq_m": round(esq, 2), "centro_m": round(centro, 2), "dir_m": round(dir_, 2),
|
||||||
|
"dist_m": round(d, 2), "lim": lim, "livre": livre,
|
||||||
|
"parar_m": PARAR_M, "livre_m": LIVRE_M}
|
||||||
|
self.foto = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 70])[1].tobytes()
|
||||||
|
cor = colorir(m, img.shape)
|
||||||
|
self.imagem_prof = cv2.imencode(".jpg", cor, [cv2.IMWRITE_JPEG_QUALITY, 70])[1].tobytes()
|
||||||
|
# Um envio por vez: se o robô estiver lento, pula este quadro em vez de enfileirar.
|
||||||
|
if self.envio_robo is None or self.envio_robo.done():
|
||||||
|
self.envio_robo = asyncio.create_task(self._avisar_robo(lim, d, livre))
|
||||||
|
|
||||||
|
async def _avisar_robo(self, lim, d, livre):
|
||||||
|
params = {"lim": lim, "ttl": TTL_MS, "d": f"{d:.2f}", "livre": livre}
|
||||||
|
try:
|
||||||
|
async with self.sessao.post(PIPE + "/c/robomovel/obstaculo", params=params,
|
||||||
|
timeout=aiohttp.ClientTimeout(total=3)) as r:
|
||||||
|
self.estado["robo"] = r.status == 200
|
||||||
|
except Exception:
|
||||||
|
self.estado["robo"] = False
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------- app -> estado e imagens
|
||||||
|
async def _laco_app(self):
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
async with self.sessao.ws_connect(PIPE + "/ws/robomovel-visao", heartbeat=20) as ws:
|
||||||
|
async for msg in ws:
|
||||||
|
if msg.type != aiohttp.WSMsgType.TEXT:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
pedido = json.loads(msg.data)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if pedido.get("tipo") == "req":
|
||||||
|
await ws.send_str(json.dumps(self._responder(pedido)))
|
||||||
|
except Exception as erro:
|
||||||
|
print("canal do app:", erro, flush=True)
|
||||||
|
await asyncio.sleep(3)
|
||||||
|
|
||||||
|
def _responder(self, pedido):
|
||||||
|
resp = {"tipo": "resp", "id": pedido.get("id"), "status": 200}
|
||||||
|
rota = pedido.get("path")
|
||||||
|
if rota == "/estado":
|
||||||
|
estado = dict(self.estado)
|
||||||
|
estado["idade_s"] = round(time.time() - estado.pop("t", 0), 1) if "t" in estado else None
|
||||||
|
resp["body"] = json.dumps(estado)
|
||||||
|
elif rota == "/imagem.jpg":
|
||||||
|
dados = self.foto if pedido.get("query", {}).get("tipo") == "foto" else self.imagem_prof
|
||||||
|
if not dados:
|
||||||
|
resp.update(status=404, body='{"error":"sem imagem ainda"}')
|
||||||
|
else:
|
||||||
|
resp.update(body_b64=base64.b64encode(dados).decode(), content_type="image/jpeg")
|
||||||
|
else:
|
||||||
|
resp.update(status=404, body='{"error":"rota nao encontrada"}')
|
||||||
|
return resp
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
asyncio.run(Visao().rodar())
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=RoboMovel anticolisao (Depth Anything V2 metrico)
|
||||||
|
After=pipe.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
WorkingDirectory=%h/visao
|
||||||
|
ExecStart=%h/visao/.venv/bin/python %h/visao/visao.py
|
||||||
|
Environment=ROTACAO=90
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
Reference in new issue
Block a user