- app/: app demo (Kivy/buildozer) da API do robo - software/: servidor RoboMovel (SLAM, profundidade, navegacao) e firmware da base movel (movido de firmware/) - simulacao/: projeto Godot do robo e script de lancamento servidor + simulacao - modelos/: planta do 5o andar do bloco D, cena Blender do corredor e modelo real do robo - partes/mdf/: chapas identificadas e nesting da base do robo (DXF/SVG/FCStd) - projeto/render, relatorio/imagens, slides: renders finais e apresentacoes de progresso - ferramentas/scripts: encaixe de chapas, planta do bloco D e render do corredor no Blender - .gitignore: ignora backups do Blender/FreeCAD e .godot/ Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
814 lines
33 KiB
Python
814 lines
33 KiB
Python
"""App de demonstração (simula o app mobile do RoboMovel) com joystick, em Kivy.
|
||
|
||
.venv/bin/python main.py [ws://IP:5000/ws/app]
|
||
|
||
Joystick da esquerda: translação (mecanum: frente/trás e lateral).
|
||
Joystick da direita: giro (horizontal).
|
||
Botões: Parar, Manual e Modelo. A imagem pode alternar entre o mapa de profundidade, a câmera
|
||
RGB, as previsões do ViNT, um mapa do mundo e a aba Opções (IP/porta do servidor). Não existe modo automático: o robô anda por
|
||
joystick (Manual) ou guiado por um modelo (ViNT/S2E).
|
||
|
||
No modo Mapa, toque no mapa para marcar A/B/C em coordenadas (x, z); "Ir" executa a rota
|
||
com o S2E (point-goal). Fora do mapa, A/B/C capturam o quadro atual da câmera como destino
|
||
(imagem + pose) e "Ir" executa a rota com o ViNT (image-goal).
|
||
|
||
A janela abre no formato de um celular em retrato (412 × 915 dp, como um Pixel 7). No Android a
|
||
orientação é travada em retrato; no desktop é só o tamanho da janela.
|
||
"""
|
||
import json
|
||
import math
|
||
import os
|
||
import sys
|
||
import threading
|
||
import time
|
||
import urllib.request
|
||
|
||
from kivy.config import Config
|
||
from kivy.utils import platform
|
||
|
||
# Precisa vir antes de qualquer outra importação do Kivy: "width/height" e "fullscreen"
|
||
# só são lidos na criação da janela. Em Android/iOS o tamanho real é o da tela.
|
||
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")
|
||
Config.set("graphics", "fullscreen", "0")
|
||
|
||
import websocket
|
||
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, Rectangle
|
||
from kivy.uix.boxlayout import BoxLayout
|
||
from kivy.uix.button import Button
|
||
from kivy.uix.image import Image
|
||
from kivy.uix.floatlayout import FloatLayout
|
||
from kivy.uix.label import Label
|
||
from kivy.uix.textinput import TextInput
|
||
from kivy.uix.widget import Widget
|
||
from io import BytesIO
|
||
|
||
URL_WS = sys.argv[1] if len(sys.argv) > 1 else "ws://127.0.0.1:5000/ws/app"
|
||
ENVIO_HZ = 20
|
||
|
||
|
||
def separar_host_porta(texto, padrao_host="127.0.0.1", padrao_porta=5000):
|
||
"""Aceita "192.168.0.10", "192.168.0.10:5000" ou "ws://192.168.0.10:5000/ws/app"."""
|
||
texto = (texto or "").strip()
|
||
for prefixo in ("ws://", "wss://", "http://", "https://"):
|
||
if texto.startswith(prefixo):
|
||
texto = texto[len(prefixo):]
|
||
texto = texto.split("/")[0]
|
||
host, porta = texto, padrao_porta
|
||
if texto.count(":") == 1:
|
||
host, resto = texto.rsplit(":", 1)
|
||
try:
|
||
porta = int(resto)
|
||
except ValueError:
|
||
host, porta = texto, padrao_porta
|
||
return host or padrao_host, porta
|
||
|
||
CORES_PONTO = {"A": (0.2, 0.8, 0.3, 1), "B": (0.95, 0.65, 0.1, 1), "C": (0.9, 0.25, 0.25, 1)}
|
||
|
||
|
||
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)
|
||
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)
|
||
|
||
|
||
class Mapa(Widget):
|
||
"""Mapa esquemático no lado do app: x para cima, z para a direita, em metros.
|
||
|
||
Um toque marca o ponto selecionado (A/B/C); arrastar move o mapa; pinça (ou a roda do mouse)
|
||
dá zoom. A escala usa a altura da área para o mapa ficar legível e mais largo que a tela.
|
||
"""
|
||
|
||
X0, X1 = -8.0, 3.0
|
||
Z0, Z1 = -8.0, 24.0
|
||
# faixas caminháveis conhecidas do cenário: (x_min, x_max, z_min, z_max)
|
||
CORREDORES = [(-0.95, 0.95, -6.6, 17.6), (-4.0, -0.95, 1.5, 3.9)]
|
||
|
||
def __init__(self, **kw):
|
||
super().__init__(**kw)
|
||
self.ativo = False
|
||
self.robo = None # (x, z, rumo)
|
||
self.trilha = []
|
||
self.pontos = {}
|
||
self.sel = "A"
|
||
self.ao_marcar = None
|
||
self.zoom = 1.0
|
||
self.pan = [0.0, 0.0]
|
||
self._toque = None
|
||
self._pos0 = None
|
||
self._pan0 = None
|
||
self._arrastou = False
|
||
self._toques = {}
|
||
self._pinch_dist = None
|
||
self._pinch_zoom = None
|
||
self.bind(pos=self._desenhar, size=self._desenhar)
|
||
|
||
def _geo_base(self):
|
||
"""Escala (px/m) e origem centralizada, antes do deslocamento do usuário."""
|
||
s = (self.height / (self.X1 - self.X0)) * self.zoom
|
||
mw = (self.Z1 - self.Z0) * s
|
||
mh = (self.X1 - self.X0) * s
|
||
ox = self.x + (self.width - mw) / 2
|
||
oy = self.y + (self.height - mh) / 2
|
||
return s, ox, oy
|
||
|
||
def _geo(self):
|
||
s, ox, oy = self._geo_base()
|
||
return s, ox + self.pan[0], oy + self.pan[1]
|
||
|
||
def _limitar_pan(self):
|
||
"""Não deixa abrir buraco entre o mapa e a borda da área visível."""
|
||
s, ox, oy = self._geo_base()
|
||
mw = (self.Z1 - self.Z0) * s
|
||
mh = (self.X1 - self.X0) * s
|
||
if mw <= self.width:
|
||
self.pan[0] = 0.0
|
||
else:
|
||
self.pan[0] = max(self.x + self.width - (ox + mw),
|
||
min(self.x - ox, self.pan[0]))
|
||
if mh <= self.height:
|
||
self.pan[1] = 0.0
|
||
else:
|
||
self.pan[1] = max(self.y + self.height - (oy + mh),
|
||
min(self.y - oy, self.pan[1]))
|
||
|
||
def centralizar(self, x=None, z=None):
|
||
"""Centraliza no robô (ou no centro do mundo, se ainda não há pose)."""
|
||
if x is None and self.robo:
|
||
x, z = self.robo[0], self.robo[1]
|
||
s, ox, oy = self._geo_base()
|
||
if x is None:
|
||
self.pan = [0.0, 0.0]
|
||
else:
|
||
self.pan = [self.center_x - (ox + (z - self.Z0) * s),
|
||
self.center_y - (oy + (self.X1 - x) * s)]
|
||
self._limitar_pan()
|
||
self._desenhar()
|
||
|
||
def _zoom_em(self, px, py, fator):
|
||
novo = max(0.6, min(6.0, self.zoom * fator))
|
||
if abs(novo - self.zoom) < 1e-4:
|
||
return
|
||
wx, wz = self.tela_para_mundo(px, py)
|
||
self.zoom = novo
|
||
s, ox, oy = self._geo_base()
|
||
self.pan[0] += px - (ox + (wz - self.Z0) * s)
|
||
self.pan[1] += py - (oy + (self.X1 - wx) * s)
|
||
self._limitar_pan()
|
||
self._desenhar()
|
||
|
||
def mundo_para_tela(self, x, z):
|
||
s, ox, oy = self._geo()
|
||
return ox + (z - self.Z0) * s, oy + (self.X1 - x) * s
|
||
|
||
def tela_para_mundo(self, px, py):
|
||
s, ox, oy = self._geo()
|
||
z = self.Z0 + (px - ox) / s
|
||
x = self.X1 - (py - oy) / s
|
||
return max(self.X0, min(self.X1, x)), max(self.Z0, min(self.Z1, z))
|
||
|
||
def _desenhar(self, *_):
|
||
self._limitar_pan()
|
||
self.canvas.clear()
|
||
s, ox, oy = self._geo()
|
||
top = oy + (self.X1 - self.X0) * s
|
||
right = ox + (self.Z1 - self.Z0) * s
|
||
with self.canvas:
|
||
Color(0.1, 0.12, 0.16)
|
||
Rectangle(pos=self.pos, size=self.size)
|
||
Color(0.17, 0.19, 0.24)
|
||
Rectangle(pos=(ox, oy), size=(right - ox, top - oy))
|
||
|
||
# corredores por onde o robô consegue passar (referência para marcar A/B/C)
|
||
Color(0.22, 0.27, 0.33)
|
||
for cx0, cx1, cz0, cz1 in self.CORREDORES:
|
||
x0, y0 = self.mundo_para_tela(cx1, cz0)
|
||
x1, y1 = self.mundo_para_tela(cx0, cz1)
|
||
Rectangle(pos=(x0, y1), size=(x1 - x0, y0 - y1))
|
||
|
||
# grade de 1 m
|
||
Color(0.26, 0.29, 0.35)
|
||
z = math.ceil(self.Z0)
|
||
while z <= self.Z1:
|
||
px = ox + (z - self.Z0) * s
|
||
Line(points=[px, oy, px, top], width=1)
|
||
z += 1
|
||
x = math.ceil(self.X0)
|
||
while x <= self.X1:
|
||
py = oy + (self.X1 - x) * s
|
||
Line(points=[ox, py, right, py], width=1)
|
||
x += 1
|
||
|
||
# trilha do robô
|
||
if len(self.trilha) > 1:
|
||
Color(0.35, 0.6, 0.85, 0.9)
|
||
pts = []
|
||
for tx, tz in self.trilha[-400:]:
|
||
pts.extend(self.mundo_para_tela(tx, tz))
|
||
Line(points=pts, width=1.2)
|
||
|
||
# pontos A/B/C
|
||
for nome, (px, pz) in self.pontos.items():
|
||
cx, cy = self.mundo_para_tela(px, pz)
|
||
r = 7 if nome == self.sel else 5
|
||
Color(*CORES_PONTO.get(nome, (1, 1, 1, 1)))
|
||
Ellipse(pos=(cx - r, cy - r), size=(2 * r, 2 * r))
|
||
if nome == self.sel:
|
||
Color(1, 1, 1, 0.9)
|
||
Line(circle=(cx, cy, r + 3), width=1.2)
|
||
|
||
# robô + rumo
|
||
if self.robo:
|
||
rx, rz, rumo = self.robo
|
||
cx, cy = self.mundo_para_tela(rx, rz)
|
||
th = math.radians(rumo or 0.0)
|
||
dx, dz = -math.sin(th), -math.cos(th) # frente no mundo Godot
|
||
fx, fz = self.mundo_para_tela(rx + dx * 0.8, rz + dz * 0.8)
|
||
Color(1, 0.85, 0.2)
|
||
Ellipse(pos=(cx - 5, cy - 5), size=(10, 10))
|
||
Line(points=[cx, cy, fx, fz], width=2)
|
||
|
||
def on_touch_down(self, toque):
|
||
if not self.ativo or not self.collide_point(*toque.pos):
|
||
return False
|
||
if getattr(toque, "is_mouse_scrolling", False):
|
||
self._zoom_em(toque.x, toque.y, 1.2 if toque.button == "scrollup" else 1 / 1.2)
|
||
return True
|
||
|
||
self._toques[toque.uid] = toque.pos
|
||
if len(self._toques) == 1:
|
||
self._toque = toque.uid
|
||
self._pos0 = toque.pos
|
||
self._pan0 = list(self.pan)
|
||
self._arrastou = False
|
||
elif len(self._toques) == 2:
|
||
(x1, y1), (x2, y2) = list(self._toques.values())[:2]
|
||
self._pinch_dist = math.hypot(x2 - x1, y2 - y1)
|
||
self._pinch_zoom = self.zoom
|
||
self._arrastou = True
|
||
return True
|
||
|
||
def on_touch_move(self, toque):
|
||
if toque.uid not in self._toques:
|
||
return False
|
||
self._toques[toque.uid] = toque.pos
|
||
|
||
if len(self._toques) >= 2:
|
||
(x1, y1), (x2, y2) = list(self._toques.values())[:2]
|
||
dist = math.hypot(x2 - x1, y2 - y1)
|
||
if self._pinch_dist and dist > 1:
|
||
alvo = self._pinch_zoom * dist / self._pinch_dist
|
||
self._zoom_em((x1 + x2) / 2, (y1 + y2) / 2, alvo / self.zoom)
|
||
self._arrastou = True
|
||
return True
|
||
|
||
if toque.uid == self._toque:
|
||
dx = toque.x - self._pos0[0]
|
||
dy = toque.y - self._pos0[1]
|
||
if not self._arrastou and math.hypot(dx, dy) > 8:
|
||
self._arrastou = True
|
||
if self._arrastou:
|
||
self.pan = [self._pan0[0] + dx, self._pan0[1] + dy]
|
||
self._limitar_pan()
|
||
self._desenhar()
|
||
return True
|
||
return False
|
||
|
||
def on_touch_up(self, toque):
|
||
if toque.uid not in self._toques:
|
||
return False
|
||
del self._toques[toque.uid]
|
||
|
||
if not self._toques:
|
||
marcar = (not self._arrastou and toque.uid == self._toque and self.ao_marcar)
|
||
self._toque = None
|
||
self._pos0 = None
|
||
self._pan0 = None
|
||
self._pinch_dist = None
|
||
if marcar:
|
||
x, z = self.tela_para_mundo(toque.x, toque.y)
|
||
self.ao_marcar(self.sel, x, z)
|
||
self._arrastou = False
|
||
return True
|
||
|
||
if len(self._toques) == 1:
|
||
uid, pos = list(self._toques.items())[0]
|
||
self._toque = uid
|
||
self._pos0 = pos
|
||
self._pan0 = list(self.pan)
|
||
self._arrastou = True
|
||
self._pinch_dist = None
|
||
return True
|
||
|
||
|
||
class Painel(BoxLayout):
|
||
def __init__(self, **kw):
|
||
super().__init__(orientation="vertical", padding=12, spacing=10, **kw)
|
||
self.servidor_host, self.servidor_porta = self._config_inicial()
|
||
self.url_ws = f"ws://{self.servidor_host}:{self.servidor_porta}/ws/app"
|
||
self.url_http = f"http://{self.servidor_host}:{self.servidor_porta}"
|
||
self.status = Label(text="conectando…", size_hint_y=None, height=88, font_size=13,
|
||
halign="left", valign="middle")
|
||
self.status.bind(size=lambda l, s: setattr(l, "text_size", s))
|
||
self.add_widget(self.status)
|
||
|
||
# alterna entre profundidade, câmera, previsão e mapa
|
||
self.fonte = "profundidade"
|
||
self._mapa_aberto = False
|
||
vista = BoxLayout(size_hint_y=None, height=42, spacing=4)
|
||
self.btn_vista = {}
|
||
for texto, fonte in (("Profund.", "profundidade"), ("Câmera", "camera"),
|
||
("Previsão", "planejamento"), ("SLAM", "slam"), ("Mapa", "mapa"),
|
||
("Opções", "opcoes")):
|
||
b = Button(text=texto, font_size=11, background_color=(0.2, 0.25, 0.35, 1))
|
||
b.bind(on_release=lambda _b, f=fonte: self._trocar_vista(f))
|
||
self.btn_vista[fonte] = b
|
||
vista.add_widget(b)
|
||
self.btn_vista["profundidade"].background_color = (0.45, 0.3, 0.7, 1)
|
||
self.add_widget(vista)
|
||
|
||
# área de cima: imagem (profundidade/câmera/previsão) ou mapa
|
||
self.caixa_imagem = FloatLayout()
|
||
self.profundidade = Image(fit_mode="contain", size_hint=(1, 1), pos_hint={"x": 0, "y": 0})
|
||
self.caixa_imagem.add_widget(self.profundidade)
|
||
self.mapa = Mapa(size_hint=(1, 1), pos_hint={"x": 0, "y": 0})
|
||
self.mapa.ao_marcar = self._marcar_ponto
|
||
self.mapa.opacity = 0
|
||
self.caixa_imagem.add_widget(self.mapa)
|
||
|
||
# aba de opções: endereço IP e porta do servidor (configuração salva no aparelho)
|
||
self.caixa_opcoes = BoxLayout(orientation="vertical", padding=12, spacing=8,
|
||
size_hint=(1, 1), pos_hint={"x": 0, "y": 0})
|
||
with self.caixa_opcoes.canvas.before:
|
||
Color(0.13, 0.15, 0.19, 1)
|
||
self._fundo_opcoes = Rectangle(pos=self.caixa_opcoes.pos,
|
||
size=self.caixa_opcoes.size)
|
||
self.caixa_opcoes.bind(pos=self._atualizar_fundo_opcoes,
|
||
size=self._atualizar_fundo_opcoes)
|
||
|
||
titulo = Label(text="Servidor", size_hint_y=None, height=28, font_size=18, bold=True)
|
||
self.caixa_opcoes.add_widget(titulo)
|
||
|
||
linha_host = BoxLayout(size_hint_y=None, height=42, spacing=8)
|
||
linha_host.add_widget(Label(text="IP / host", font_size=14, size_hint_x=0.32))
|
||
self.campo_host = TextInput(text=self.servidor_host, multiline=False, font_size=15,
|
||
size_hint_x=0.68, write_tab=False, padding=[8, 10, 8, 10])
|
||
linha_host.add_widget(self.campo_host)
|
||
self.caixa_opcoes.add_widget(linha_host)
|
||
|
||
linha_porta = BoxLayout(size_hint_y=None, height=42, spacing=8)
|
||
linha_porta.add_widget(Label(text="Porta", font_size=14, size_hint_x=0.32))
|
||
self.campo_porta = TextInput(text=str(self.servidor_porta), multiline=False, font_size=15,
|
||
size_hint_x=0.68, write_tab=False, padding=[8, 10],
|
||
input_filter="int")
|
||
linha_porta.add_widget(self.campo_porta)
|
||
self.caixa_opcoes.add_widget(linha_porta)
|
||
|
||
botoes_servidor = BoxLayout(size_hint_y=None, height=44, spacing=8)
|
||
b_aplicar = Button(text="Aplicar e conectar", font_size=14,
|
||
background_color=(0.45, 0.3, 0.7, 1))
|
||
b_aplicar.bind(on_release=lambda *_: self._aplicar_servidor())
|
||
botoes_servidor.add_widget(b_aplicar)
|
||
b_local = Button(text="Local", font_size=13, size_hint_x=0.35,
|
||
background_color=(0.3, 0.32, 0.4, 1))
|
||
b_local.bind(on_release=lambda *_: self._usar_local())
|
||
botoes_servidor.add_widget(b_local)
|
||
self.caixa_opcoes.add_widget(botoes_servidor)
|
||
|
||
self.lbl_servidor = Label(text=self.url_ws, size_hint_y=None, height=40, font_size=11,
|
||
halign="left", valign="middle")
|
||
self.lbl_servidor.bind(size=lambda l, s: setattr(l, "text_size", s))
|
||
self.caixa_opcoes.add_widget(self.lbl_servidor)
|
||
nota = Label(text="No celular, use o IP do PC na mesma rede Wi-Fi.", size_hint_y=None,
|
||
height=40, font_size=11, halign="left", valign="middle",
|
||
color=(0.7, 0.72, 0.78, 1))
|
||
nota.bind(size=lambda l, s: setattr(l, "text_size", s))
|
||
self.caixa_opcoes.add_widget(nota)
|
||
self.add_widget(self.caixa_imagem)
|
||
|
||
# joysticks
|
||
self.caixa_joysticks = BoxLayout(spacing=10)
|
||
self.mover = Joystick()
|
||
self.girar = Joystick(so_horizontal=True)
|
||
self.caixa_joysticks.add_widget(self.mover)
|
||
self.caixa_joysticks.add_widget(self.girar)
|
||
self.add_widget(self.caixa_joysticks)
|
||
|
||
# A/B/C + Ir + Limpar (captura de imagem ou marcação no mapa)
|
||
self.capturados = []
|
||
self.pontos = {} # nome -> (x, z) marcados no mapa
|
||
self.ponto_sel = "A"
|
||
self.trilha = []
|
||
self._ult_pos = None
|
||
self.btn_captura = {}
|
||
rota = BoxLayout(size_hint_y=None, height=44, spacing=8)
|
||
for nome in ("A", "B", "C"):
|
||
b = Button(text=nome, font_size=15, background_color=(0.3, 0.32, 0.4, 1))
|
||
b.bind(on_release=lambda _b, n=nome: self._tecla_ponto(n))
|
||
self.btn_captura[nome] = b
|
||
rota.add_widget(b)
|
||
ir = Button(text="Ir", font_size=15, background_color=(0.45, 0.3, 0.7, 1))
|
||
ir.bind(on_release=lambda *_: self._executar_rota())
|
||
rota.add_widget(ir)
|
||
limpar = Button(text="Limpar", font_size=13, background_color=(0.35, 0.25, 0.25, 1))
|
||
limpar.bind(on_release=lambda *_: self._limpar_capturas())
|
||
rota.add_widget(limpar)
|
||
self.add_widget(rota)
|
||
|
||
botoes = BoxLayout(size_hint_y=None, height=64, spacing=10)
|
||
for texto, cmd, cor in [("Parar", {"tipo": "parar"}, (0.8, 0.2, 0.2, 1)),
|
||
("Manual", {"tipo": "modo", "modo": "manual"}, (0.3, 0.6, 0.3, 1)),
|
||
("Modelo", {"tipo": "modo", "modo": "modelo"}, (0.45, 0.3, 0.7, 1))]:
|
||
b = Button(text=texto, background_color=cor, font_size=16)
|
||
b.bind(on_release=lambda _b, c=cmd: self.enviar(c))
|
||
botoes.add_widget(b)
|
||
self.add_widget(botoes)
|
||
|
||
self.ws = None
|
||
self._ultimo_joy = None
|
||
threading.Thread(target=self._laco_ws, daemon=True).start()
|
||
threading.Thread(target=self._laco_profundidade, daemon=True).start()
|
||
Clock.schedule_interval(self._enviar_joystick, 1.0 / ENVIO_HZ)
|
||
|
||
# ------------------------------------------------------------ configuração
|
||
def _config_inicial(self):
|
||
host, porta = separar_host_porta(URL_WS)
|
||
try:
|
||
with open(self._caminho_config(), "r", encoding="utf-8") as arquivo:
|
||
cfg = json.load(arquivo)
|
||
host = str(cfg.get("host") or host)
|
||
porta = int(cfg.get("porta") or porta)
|
||
except Exception:
|
||
pass
|
||
# argumento explícito na linha de comando tem prioridade sobre o que está salvo
|
||
if len(sys.argv) > 1 and sys.argv[1].startswith(("ws://", "http://")):
|
||
host, porta = separar_host_porta(sys.argv[1])
|
||
return host, porta
|
||
|
||
def _caminho_config(self):
|
||
try:
|
||
base = App.get_running_app().user_data_dir
|
||
except Exception:
|
||
base = os.path.expanduser("~")
|
||
try:
|
||
os.makedirs(base, exist_ok=True)
|
||
except Exception:
|
||
pass
|
||
return os.path.join(base, "servidor.json")
|
||
|
||
def _salvar_config(self):
|
||
try:
|
||
with open(self._caminho_config(), "w", encoding="utf-8") as arquivo:
|
||
json.dump({"host": self.servidor_host, "porta": self.servidor_porta}, arquivo)
|
||
except Exception as erro:
|
||
print("não salvou a configuração do servidor:", erro)
|
||
|
||
def _atualizar_fundo_opcoes(self, *_):
|
||
self._fundo_opcoes.pos = self.caixa_opcoes.pos
|
||
self._fundo_opcoes.size = self.caixa_opcoes.size
|
||
|
||
def _aplicar_servidor(self):
|
||
host, _ = separar_host_porta(self.campo_host.text, self.servidor_host,
|
||
self.servidor_porta)
|
||
porta_txt = self.campo_porta.text.strip()
|
||
if not porta_txt.isdigit() or not (1 <= int(porta_txt) <= 65535):
|
||
self._mostrar_texto("porta inválida: use um número entre 1 e 65535")
|
||
return
|
||
if not host:
|
||
self._mostrar_texto("informe o IP ou host do servidor")
|
||
return
|
||
self.servidor_host = host
|
||
self.servidor_porta = int(porta_txt)
|
||
self.url_ws = f"ws://{self.servidor_host}:{self.servidor_porta}/ws/app"
|
||
self.url_http = f"http://{self.servidor_host}:{self.servidor_porta}"
|
||
self.campo_host.text = self.servidor_host
|
||
self.campo_porta.text = str(self.servidor_porta)
|
||
self.lbl_servidor.text = f"atual: {self.url_ws}"
|
||
self._salvar_config()
|
||
self._reconectar()
|
||
self._trocar_vista("profundidade")
|
||
self._mostrar_texto(f"conectando a {self.servidor_host}:{self.servidor_porta}…")
|
||
|
||
def _usar_local(self):
|
||
self.campo_host.text = "127.0.0.1"
|
||
self.campo_porta.text = "5000"
|
||
self._aplicar_servidor()
|
||
|
||
def _reconectar(self):
|
||
"""Fecha o WebSocket atual; a thread de conexão tenta de novo com a URL nova."""
|
||
ws, self.ws = self.ws, None
|
||
if ws is not None:
|
||
try:
|
||
ws.close()
|
||
except Exception:
|
||
pass
|
||
|
||
# ------------------------------------------------------------ rede
|
||
def enviar(self, cmd):
|
||
try:
|
||
if self.ws:
|
||
self.ws.send(json.dumps(cmd))
|
||
except Exception:
|
||
pass
|
||
|
||
def _enviar_joystick(self, _dt):
|
||
vx, vy = self.mover.valor
|
||
giro = -self.girar.valor[0] # manche para a direita = girar no sentido horário
|
||
joy = (round(vx, 2), round(vy, 2), round(giro, 2))
|
||
# manda enquanto houver movimento e uma vez quando volta ao centro
|
||
if any(joy) or joy != self._ultimo_joy:
|
||
self.enviar({"tipo": "joystick", "vx": joy[0], "vy": joy[1], "giro": joy[2]})
|
||
self._ultimo_joy = joy
|
||
|
||
def _laco_ws(self):
|
||
while True:
|
||
try:
|
||
ws = websocket.create_connection(self.url_ws, timeout=5)
|
||
self.ws = ws
|
||
ws.settimeout(None)
|
||
while True:
|
||
d = json.loads(ws.recv())
|
||
if d.get("tipo") == "erro":
|
||
self._mostrar_texto(d.get("erro", "erro"))
|
||
elif d.get("tipo") == "estado":
|
||
self._mostrar_estado(d)
|
||
except Exception as e:
|
||
self.ws = None
|
||
self._mostrar_texto(f"sem conexão com {self.url_ws} ({e.__class__.__name__}); tentando de novo…")
|
||
time.sleep(2)
|
||
|
||
# ------------------------------------------------------------ vistas
|
||
def _trocar_vista(self, fonte):
|
||
self.fonte = fonte
|
||
for f, b in self.btn_vista.items():
|
||
b.background_color = (0.45, 0.3, 0.7, 1) if f == fonte else (0.2, 0.25, 0.35, 1)
|
||
self.profundidade.texture = None
|
||
self.mapa.ativo = fonte == "mapa"
|
||
self.mapa.opacity = 1 if self.mapa.ativo else 0
|
||
self.profundidade.opacity = 0 if fonte in ("mapa", "opcoes") else 1
|
||
if fonte == "opcoes":
|
||
if self.caixa_opcoes.parent is None:
|
||
self.caixa_imagem.add_widget(self.caixa_opcoes)
|
||
self.campo_host.text = self.servidor_host
|
||
self.campo_porta.text = str(self.servidor_porta)
|
||
self.lbl_servidor.text = f"atual: {self.url_ws}"
|
||
self._mostrar_texto("configuração do servidor")
|
||
else:
|
||
if self.caixa_opcoes.parent is not None:
|
||
self.caixa_imagem.remove_widget(self.caixa_opcoes)
|
||
if fonte == "mapa":
|
||
if not self._mapa_aberto:
|
||
self.mapa.centralizar()
|
||
self._mapa_aberto = True
|
||
self.mapa.sel = self.ponto_sel
|
||
self.mapa._desenhar()
|
||
self._mostrar_texto("mapa: toque para marcar · arraste para mover · pinça/scroll para zoom")
|
||
elif fonte == "planejamento":
|
||
self._mostrar_texto("previsão do modelo: aguardando…")
|
||
elif fonte == "camera":
|
||
self._mostrar_texto("câmera do robô (RGB)")
|
||
elif fonte == "slam":
|
||
self._mostrar_texto("mapa do V-SLAM: aguardando…")
|
||
|
||
# ------------------------------------------------------------ A/B/C
|
||
def _tecla_ponto(self, nome):
|
||
if self.fonte == "mapa":
|
||
self.ponto_sel = nome
|
||
self.mapa.sel = nome
|
||
self.mapa._desenhar()
|
||
self._atualizar_botoes()
|
||
self._mostrar_texto(f"toque no mapa para marcar {nome}")
|
||
else:
|
||
self._capturar(nome)
|
||
|
||
def _marcar_ponto(self, nome, x, z):
|
||
self.pontos[nome] = (x, z)
|
||
self.mapa.pontos = self.pontos
|
||
self.mapa._desenhar()
|
||
self._mostrar_texto(f"{nome} em x={x:.2f} m, z={z:.2f} m")
|
||
# seleciona o próximo ponto ainda não marcado
|
||
for proximo in ("A", "B", "C"):
|
||
if proximo not in self.pontos:
|
||
self.ponto_sel = proximo
|
||
self.mapa.sel = proximo
|
||
break
|
||
self._atualizar_botoes()
|
||
|
||
def _atualizar_botoes(self):
|
||
for nome, b in self.btn_captura.items():
|
||
if self.fonte == "mapa":
|
||
marcado = nome in self.pontos
|
||
b.text = f"{nome} ok" if marcado else nome
|
||
if marcado:
|
||
b.background_color = (0.25, 0.55, 0.3, 1)
|
||
elif nome == self.ponto_sel:
|
||
b.background_color = (0.45, 0.3, 0.7, 1)
|
||
else:
|
||
b.background_color = (0.3, 0.32, 0.4, 1)
|
||
else:
|
||
marcado = nome in self.capturados
|
||
b.text = f"{nome} ok" if marcado else nome
|
||
b.background_color = (0.25, 0.55, 0.3, 1) if marcado else (0.3, 0.32, 0.4, 1)
|
||
|
||
def _capturar(self, nome):
|
||
"""Pede ao servidor para guardar o quadro RGB atual como destino A, B ou C (com a pose)."""
|
||
self._mostrar_texto(f"capturando {nome}…")
|
||
|
||
def tarefa():
|
||
try:
|
||
req = urllib.request.Request(self.url_http + f"/api/objetivo?nome={nome}", data=b"", method="POST")
|
||
urllib.request.urlopen(req, timeout=3).read()
|
||
self._mostrar_texto(f"destino {nome} capturado")
|
||
except Exception as e:
|
||
self._mostrar_texto(f"não capturei {nome}: {e.__class__.__name__}")
|
||
|
||
threading.Thread(target=tarefa, daemon=True).start()
|
||
|
||
def _executar_rota(self):
|
||
if self.fonte == "mapa":
|
||
pontos = [list(self.pontos[n]) for n in ("A", "B", "C") if n in self.pontos]
|
||
if not pontos:
|
||
self._mostrar_texto("marque pelo menos um ponto no mapa")
|
||
return
|
||
self._trocar_vista("planejamento")
|
||
self.enviar({"tipo": "rota_mapa", "pontos": pontos})
|
||
return
|
||
if not self.capturados:
|
||
self._mostrar_texto("capture A, B ou C antes de executar")
|
||
return
|
||
self._trocar_vista("planejamento")
|
||
self.enviar({"tipo": "rota", "pontos": list(self.capturados)})
|
||
|
||
def _limpar_capturas(self):
|
||
self.pontos.clear()
|
||
self.mapa.pontos = self.pontos
|
||
self.mapa._desenhar()
|
||
self._atualizar_botoes()
|
||
|
||
def tarefa():
|
||
try:
|
||
req = urllib.request.Request(self.url_http + "/api/objetivo", method="DELETE")
|
||
urllib.request.urlopen(req, timeout=3).read()
|
||
except Exception:
|
||
pass
|
||
|
||
threading.Thread(target=tarefa, daemon=True).start()
|
||
self._mostrar_texto("capturas e pontos apagados")
|
||
|
||
def _laco_profundidade(self):
|
||
caminhos = {"profundidade": "/api/profundidade.jpg", "camera": "/api/camera.jpg",
|
||
"planejamento": "/api/planejamento.jpg", "slam": "/api/slam.jpg"}
|
||
while True:
|
||
if self.fonte in ("mapa", "opcoes"):
|
||
time.sleep(0.2)
|
||
continue
|
||
try:
|
||
caminho = caminhos.get(self.fonte, "/api/profundidade.jpg")
|
||
dado = urllib.request.urlopen(self.url_http + caminho, timeout=2).read()
|
||
self._mostrar_imagem(dado)
|
||
except Exception:
|
||
pass
|
||
time.sleep(0.15)
|
||
|
||
# ------------------------------------------------------------ tela
|
||
@mainthread
|
||
def _mostrar_estado(self, d):
|
||
r = d.get("robo") or {}
|
||
robo = "conectado" if d.get("conectado") else "desconectado"
|
||
pos = f"x={r.get('x', '?')} z={r.get('z', '?')} rumo={r.get('rumo', '?')}°" if r else ""
|
||
acao = f" · {r['acao']}" if r.get("acao") else ""
|
||
|
||
# mapa: pose, trilha e pontos
|
||
if r.get("x") is not None and r.get("z") is not None:
|
||
self.mapa.robo = (float(r["x"]), float(r["z"]), float(r.get("rumo") or 0.0))
|
||
if self._ult_pos is None or math.hypot(r["x"] - self._ult_pos[0], r["z"] - self._ult_pos[1]) > 0.05:
|
||
self.trilha.append((float(r["x"]), float(r["z"])))
|
||
self._ult_pos = (float(r["x"]), float(r["z"]))
|
||
self.mapa.trilha = self.trilha
|
||
self.mapa._desenhar()
|
||
|
||
extra = ""
|
||
if d.get("modo") == "s2e":
|
||
extra = f" · S2E {d.get('ms_s2e', 0)} ms"
|
||
else:
|
||
params = d.get("parametros_modelo") or 0
|
||
if params:
|
||
extra = f" · ViNT {params / 1e6:.0f}M {d.get('ms_modelo', 0)} ms"
|
||
if d.get("objetivo_definido"):
|
||
extra += " · objetivo ok"
|
||
self.status.text = (f"robô {robo} · modo [b]{d.get('modo')}[/b] · {pos}{acao}\n"
|
||
f"profundidade {d.get('ms_profundidade', 0)} ms · câmera {d.get('fps_camera', 0)} fps{extra}")
|
||
|
||
rota = d.get("rota") or {}
|
||
pontos_img = rota.get("pontos") or []
|
||
if pontos_img:
|
||
alvo = rota.get("alvo")
|
||
self.status.text += "\nrota " + "→".join(pontos_img) + " · " + (f"alvo {alvo}" if alvo else "concluída")
|
||
rm = d.get("rota_mapa") or {}
|
||
pontos_mapa = rm.get("pontos") or []
|
||
if pontos_mapa:
|
||
i = rm.get("alvo", 0)
|
||
alvo = f"ponto {i + 1}/{len(pontos_mapa)}" if i < len(pontos_mapa) else "fim"
|
||
self.status.text += f"\nmapa S2E · {len(pontos_mapa)} pontos · alvo {alvo}"
|
||
sl = d.get("slam") or {}
|
||
if self.fonte == "slam" and sl:
|
||
erro = f" · erro {sl['erro_m']} m" if "erro_m" in sl else ""
|
||
self.status.text += (f"\nV-SLAM x={sl.get('x')} z={sl.get('z')} rumo={sl.get('rumo')}° · "
|
||
f"{sl.get('ms', 0)} ms · {sl.get('inliers', 0)} pontos{erro}")
|
||
self.status.markup = True
|
||
|
||
self.capturados = list(d.get("objetivos") or [])
|
||
self._atualizar_botoes()
|
||
|
||
@mainthread
|
||
def _mostrar_texto(self, t):
|
||
self.status.text = t
|
||
|
||
@mainthread
|
||
def _mostrar_imagem(self, dado):
|
||
self.profundidade.texture = CoreImage(BytesIO(dado), ext="jpg").texture
|
||
|
||
|
||
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: # sem pyjnius ou fora de uma Activity: segue como está
|
||
print("não travou a orientação em retrato:", erro)
|
||
|
||
|
||
class AppRoboMovel(App):
|
||
title = "RoboMovel · joystick (demo)"
|
||
|
||
def build(self):
|
||
Window.clearcolor = (0.1, 0.11, 0.14, 1)
|
||
travar_retrato()
|
||
return Painel()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
AppRoboMovel().run()
|