Base movel: anticolisao com ESP32-CAM e Depth Anything V2 na VPS

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

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

No files matched your search

+120 -1
View File
@@ -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
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 os
import socket
@@ -36,11 +42,13 @@ if platform not in ("android", "ios"):
from kivy.app import App
from kivy.clock import Clock, mainthread
from kivy.core.image import Image as CoreImage
from kivy.core.window import Window
from kivy.graphics import Color, Ellipse, Line
from kivy.metrics import dp, sp
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.image import Image
from kivy.uix.label import Label
from kivy.uix.slider import Slider
from kivy.uix.textinput import TextInput
@@ -57,6 +65,8 @@ PORTA_DESCOBERTA = 4210
FALHAS_PARA_PROCURAR = 3
PIPE_HOST = "pipe.ovelha.cloud"
PIPE_CANAL = "robomovel"
VISAO_URL = f"https://{PIPE_HOST}/c/robomovel-visao"
VISAO_IMAGEM_S = 0.35
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))
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):
def __init__(self, **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)
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.add_widget(self.lbl_vel)
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
threading.Thread(target=self._laco_envio, 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)
# ------------------------------------------------------------ configuração
@@ -337,6 +389,70 @@ class Painel(BoxLayout):
if salvar:
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
def _ler_joysticks(self, _dt):
novo = comando_dos_joysticks(self.mover.valor, self.girar.valor, self.vel_max)
@@ -385,10 +501,13 @@ class Painel(BoxLayout):
while True:
try:
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"
else:
texto = "Parado"
self._mostrar_anticolisao(d.get("anticolisao"))
texto += f"\n{self.host} · rede {d.get('ssid') or '-'} · fw {d.get('fw', '?')}"
self._falhas = 0
if not self._procurando: