"""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=&ttl=&d=&livre= 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())