"""App de joystick do RoboMovel para o firmware ESP32 (API REST), em Kivy. ../robomovel-demo-api-app/.venv/bin/python main.py [IP_DO_ROBO] Joystick da esquerda: frente/trás e lateral (mecanum). Joystick da direita: giro. O firmware aceita um sentido por vez, então vale o eixo mais inclinado (sem diagonais). Enquanto um joystick está inclinado, o app repete o comando a cada ENVIO_S com duração DURACAO_MS; se a conexão cair, o robô para sozinho quando essa duração acaba. Soltar os joysticks envia /stop. Descoberta: o app manda "ROBOMOVEL?" em broadcast UDP (porta 4210) e usa o IP de quem responder. Funciona em qualquer faixa de IP (192.168.x, 10.x...), sem supor a máscara da rede. 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/. 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 import ssl import sys import threading import time import urllib.parse import urllib.request from kivy.config import Config from kivy.utils import platform RESOLUCAO_CELULAR = (412, 915) # retrato, em dp if platform not in ("android", "ios"): Config.set("graphics", "width", str(RESOLUCAO_CELULAR[0])) Config.set("graphics", "height", str(RESOLUCAO_CELULAR[1])) Config.set("graphics", "resizable", "1") 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 from kivy.uix.widget import Widget HOST_PADRAO = sys.argv[1] if len(sys.argv) > 1 else "192.168.0.84" VEL_MIN = 100 # passos/s (limites do firmware) VEL_MAX = 1000 ZONA_MORTA = 0.2 ENVIO_S = 0.15 # intervalo entre comandos repetidos DURACAO_MS = 400 # duração de cada comando (margem para atrasos da rede) TIMEOUT_S = 1.5 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(): """O Python do Android não traz certificados de CA; usa os do pacote certifi.""" try: import certifi return ssl.create_default_context(cafile=certifi.where()) except ImportError: return ssl.create_default_context() SSL_CONTEXTO = contexto_ssl() def url_base(host): if PIPE_HOST in host: return f"https://{PIPE_HOST}/c/{PIPE_CANAL}" return f"http://{host}" def enderecos_broadcast(): """Broadcast de cada interface ativa, com a máscara real dela, mais 255.255.255.255. O 255.255.255.255 sozinho não basta: se o celular for o roteador da rede (hotspot), o Android pode mandá-lo pelos dados móveis em vez da rede Wi-Fi do robô. """ lista = [] if platform == "android": try: from jnius import autoclass interfaces = autoclass("java.net.NetworkInterface").getNetworkInterfaces() while interfaces.hasMoreElements(): interface = interfaces.nextElement() if not interface.isUp() or interface.isLoopback(): continue for endereco in interface.getInterfaceAddresses().toArray(): broadcast = endereco.getBroadcast() if broadcast is not None: lista.append(broadcast.getHostAddress()) except Exception as erro: print("não listou as interfaces:", erro) lista.append("255.255.255.255") return list(dict.fromkeys(lista)) def descobrir_robo(espera_s=1.5, tentativas=3): """Broadcast na rede local; devolve (ip, status) do primeiro robô que responder, ou None.""" destinos = enderecos_broadcast() with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.bind(("", 0)) sock.settimeout(espera_s) for _ in range(tentativas): for destino in destinos: try: sock.sendto(b"ROBOMOVEL?", (destino, PORTA_DESCOBERTA)) except OSError: pass try: dados, (ip, _porta) = sock.recvfrom(1024) return ip, json.loads(dados) except (socket.timeout, ValueError): continue return None class Joystick(Widget): """Joystick virtual: posição do manche normalizada em -1..1 (x para a direita, y para cima).""" def __init__(self, so_horizontal=False, **kw): super().__init__(**kw) self.so_horizontal = so_horizontal self.valor = (0.0, 0.0) self._toque = None self.bind(pos=self._desenhar, size=self._desenhar) @property def _raio(self): return min(self.width, self.height) * 0.42 def _desenhar(self, *_): self.canvas.clear() cx, cy, r = self.center_x, self.center_y, self._raio mx, my = cx + self.valor[0] * r, cy + self.valor[1] * r with self.canvas: Color(0.22, 0.24, 0.3) Ellipse(pos=(cx - r, cy - r), size=(2 * r, 2 * r)) Color(0.4, 0.43, 0.5) Line(circle=(cx, cy, r), width=1.5) if self.so_horizontal: Line(points=[cx - r, cy, cx + r, cy], width=1) else: Line(points=[cx - r, cy, cx + r, cy], width=1) Line(points=[cx, cy - r, cx, cy + r], width=1) Color(0.95, 0.75, 0.2) Ellipse(pos=(mx - r * 0.35, my - r * 0.35), size=(r * 0.7, r * 0.7)) def _atualizar(self, toque): dx = (toque.x - self.center_x) / self._raio dy = 0.0 if self.so_horizontal else (toque.y - self.center_y) / self._raio m = max(1.0, (dx * dx + dy * dy) ** 0.5) self.valor = (dx / m, dy / m) self._desenhar() def on_touch_down(self, toque): if self.collide_point(*toque.pos) and self._toque is None: self._toque = toque.uid self._atualizar(toque) return True return super().on_touch_down(toque) def on_touch_move(self, toque): if toque.uid == self._toque: self._atualizar(toque) return True return super().on_touch_move(toque) def on_touch_up(self, toque): if toque.uid == self._toque: self._toque = None self.valor = (0.0, 0.0) self._desenhar() return True return super().on_touch_up(toque) def comando_dos_joysticks(mover, girar, vel_max): """Escolhe o eixo mais inclinado e devolve (dir, velocidade) ou None se estiver no centro.""" x, y = mover w = girar[0] eixos = [ (abs(y), "frente" if y > 0 else "tras"), (abs(x), "direita" if x > 0 else "esquerda"), (abs(w), "giro_direita" if w > 0 else "giro_esquerda"), ] intensidade, direcao = max(eixos) if intensidade < ZONA_MORTA: return None fracao = (intensidade - ZONA_MORTA) / (1 - ZONA_MORTA) 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) cfg = self._ler_config() self.host = cfg.get("host", HOST_PADRAO) self.vel_max = int(cfg.get("vel_max", 400)) self.status = Label(text="conectando…", size_hint_y=None, height=dp(70), font_size=sp(14), halign="left", valign="middle") self.status.bind(size=lambda l, s: setattr(l, "text_size", s)) self.add_widget(self.status) linha_host = BoxLayout(size_hint_y=None, height=dp(44), spacing=dp(8)) linha_host.add_widget(Label(text="Robô", font_size=sp(14), size_hint_x=0.22)) self.campo_host = TextInput(text=self.host, multiline=False, font_size=sp(15), write_tab=False, padding=[dp(8), dp(10)]) self.campo_host.bind(on_text_validate=lambda *_: self._aplicar_host()) linha_host.add_widget(self.campo_host) b_ok = Button(text="OK", size_hint_x=0.16, background_color=(0.45, 0.3, 0.7, 1)) b_ok.bind(on_release=lambda *_: self._aplicar_host()) linha_host.add_widget(b_ok) b_procurar = Button(text="Procurar", size_hint_x=0.28, font_size=sp(14), background_color=(0.3, 0.6, 0.3, 1)) b_procurar.bind(on_release=lambda *_: self._procurar()) 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, size_hint_y=None, height=dp(40)) self.slider.bind(value=self._mudar_vel) self.add_widget(self.slider) self._mudar_vel(self.slider, self.slider.value, salvar=False) dicas = BoxLayout(size_hint_y=None, height=dp(24)) dicas.add_widget(Label(text="Mover", font_size=sp(13), color=(0.7, 0.72, 0.78, 1))) dicas.add_widget(Label(text="Girar", font_size=sp(13), color=(0.7, 0.72, 0.78, 1))) self.add_widget(dicas) joysticks = BoxLayout(spacing=dp(10)) self.mover = Joystick() self.girar = Joystick(so_horizontal=True) joysticks.add_widget(self.mover) joysticks.add_widget(self.girar) self.add_widget(joysticks) parar = Button(text="PARAR", size_hint_y=None, height=dp(72), font_size=sp(20), bold=True, background_color=(0.8, 0.2, 0.2, 1)) parar.bind(on_release=lambda *_: self._parar()) self.add_widget(parar) self._comando = None # (dir, vel) atual, lido pela thread de envio self._parar_pendente = False self._evento = threading.Event() self._procurando = False self._falhas = 0 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 def _caminho_config(self): return os.path.join(App.get_running_app().user_data_dir, "config.json") def _ler_config(self): try: with open(self._caminho_config(), encoding="utf-8") as f: return json.load(f) except Exception: return {} def _salvar_config(self): try: with open(self._caminho_config(), "w", encoding="utf-8") as f: json.dump({"host": self.host, "vel_max": self.vel_max}, f) except Exception as erro: print("não salvou a configuração:", erro) def _aplicar_host(self): texto = self.campo_host.text.strip() for prefixo in ("http://", "https://"): if texto.startswith(prefixo): texto = texto[len(prefixo):] self.host = texto.split("/")[0] or HOST_PADRAO self.campo_host.text = self.host self._salvar_config() self._mostrar("conectando a " + self.host + "…") def _procurar(self): if self._procurando: return self._procurando = True self._mostrar("procurando o robô na rede…") threading.Thread(target=self._laco_procura, daemon=True).start() def _laco_procura(self): try: achado = descobrir_robo() except OSError as erro: achado = None self._mostrar(f"sem rede para procurar: {erro}") if achado: ip, dados = achado self.host = ip self._salvar_config() self._mostrar_host(ip) self._mostrar(f"robô encontrado em {ip} (rede {dados.get('ssid') or '-'})") elif self._pipe_responde(): self.host = PIPE_HOST self._salvar_config() self._mostrar_host(PIPE_HOST) self._mostrar("robô fora da rede local: usando a internet (pipe.ovelha.cloud)") else: self._mostrar("robô não encontrado na rede local nem em pipe.ovelha.cloud") self._falhas = 0 self._proxima_procura = time.monotonic() + (0 if achado else 10) self._procurando = False def _pipe_responde(self): try: url = url_base(PIPE_HOST) + "/status" with urllib.request.urlopen(url, timeout=5, context=SSL_CONTEXTO) as r: return "fw" in json.load(r) except Exception: return False @mainthread def _mostrar_host(self, ip): self.campo_host.text = ip def _mudar_vel(self, _slider, valor, salvar=True): self.vel_max = int(valor) self.lbl_vel.text = f"Velocidade máxima: {self.vel_max} passos/s" 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) antigo = self._comando self._comando = novo if novo is None and antigo is not None: self._parar_pendente = True # Só acorda a thread quando o sentido muda; o resto vai no ritmo de ENVIO_S. if (novo and novo[0]) != (antigo and antigo[0]): self._evento.set() def _parar(self): self._comando = None self._parar_pendente = True self._evento.set() def _http(self, metodo, rota, params=None): url = url_base(self.host) + rota if params: url += "?" + urllib.parse.urlencode(params) req = urllib.request.Request(url, method=metodo) pela_internet = PIPE_HOST in self.host with urllib.request.urlopen(req, timeout=4 if pela_internet else TIMEOUT_S, context=SSL_CONTEXTO if pela_internet else None) as r: return json.load(r) def _laco_envio(self): while True: self._evento.wait(ENVIO_S) self._evento.clear() try: if self._parar_pendente: self._parar_pendente = False self._http("POST", "/stop") comando = self._comando if comando: direcao, vel = comando # Pela internet a latência é maior: o comando dura mais para não engasgar. ms = DURACAO_MS * 2 if PIPE_HOST in self.host else DURACAO_MS self._http("POST", "/move", {"dir": direcao, "speed": vel, "ms": ms}) except Exception as erro: self._mostrar(f"sem resposta do robô ({self.host}): {erro}") self._evento.wait(0.5) def _laco_status(self): while True: try: d = self._http("GET", "/status") 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: self._mostrar(texto) except Exception as erro: self._falhas += 1 if (self._falhas >= FALHAS_PARA_PROCURAR and not self._procurando and time.monotonic() >= self._proxima_procura): self._procurar() elif not self._procurando: self._mostrar(f"sem resposta do robô ({self.host}): {erro}") threading.Event().wait(1.0) @mainthread def _mostrar(self, texto): self.status.text = texto def travar_retrato(): """Android: trava a Activity em retrato. No desktop/iOS não faz nada.""" if platform != "android": return try: from jnius import autoclass ActivityInfo = autoclass("android.content.pm.ActivityInfo") atividade = autoclass("org.kivy.android.PythonActivity").mActivity atividade.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) except Exception as erro: print("não travou a orientação em retrato:", erro) class AppJoystick(App): title = "RoboMovel · joystick (ESP32)" def build(self): Window.clearcolor = (0.1, 0.11, 0.14, 1) travar_retrato() return Painel() def on_stop(self): try: self.root._http("POST", "/stop") except Exception: pass if __name__ == "__main__": AppJoystick().run()