Base movel: firmware ESP32 com API REST, OTA e canal pipe.ovelha.cloud
- software/firmware/RoboMovel_CNCV3_ESP32_REST: firmware para Wemos D1 R32 + CNC Shield V3 (4 NEMA17 mecanum), API REST (/move, /stop, /status, /wifi), redes Wi-Fi salvas, gravacao pelo Wi-Fi (ota.sh), descoberta por broadcast UDP 4210 e cliente do canal publico pipe.ovelha.cloud. Senhas das redes padrao ficam em redes_padrao.h (fora do git). - software/pipe-ovelha: servidor do canal publico (aiohttp) com nginx e servico systemd. - app/robomovel-esp32-joystick-app: app Kivy so com joystick, busca automatica do robo na rede local e uso do pipe.ovelha.cloud pela internet. - compilar_apk.sh: corrige caminhos do autotools local (autom4te.cfg e libtoolize). - Remove backup .lbrn2 da chapa base.
This commit is contained in:
1 parent
6405625c1a
commit
43fae8237a
19 files changed
+1601
-6461
No files matched your search
@@ -57,9 +57,10 @@ if ! command -v autoreconf >/dev/null 2>&1; then
|
||||
chmod +x "$AUTOTOOLS/usr/bin/$f"
|
||||
done
|
||||
(cd "$AUTOTOOLS/usr/bin" && ln -sf automake-1.16 automake && ln -sf aclocal-1.16 aclocal)
|
||||
# autom4te.cfg é lido em tempo de execução e também tem caminho fixo.
|
||||
sed -i "s|/usr/share|$AUTOTOOLS/usr/share|g" \
|
||||
"$AUTOTOOLS/usr/share/autoconf/autom4te.cfg"
|
||||
# libtoolize é shell (não passa pelo laço acima) e também tem /usr/share fixo.
|
||||
sed -i "s|=\"/usr/share|=\"$AUTOTOOLS/usr/share|g" "$AUTOTOOLS/usr/bin/libtoolize"
|
||||
# autom4te.cfg também tem caminho fixo, mas já foi corrigido no laço acima
|
||||
# (fica em usr/share); corrigir de novo duplicaria o prefixo.
|
||||
fi
|
||||
export PATH="$AUTOTOOLS/usr/bin:$PATH"
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.venv/
|
||||
.buildozer/
|
||||
.buildozer-venv/
|
||||
__pycache__/
|
||||
bin/*.apk
|
||||
build*.log
|
||||
@@ -0,0 +1,24 @@
|
||||
# App de joystick do RoboMovel (ESP32, Kivy)
|
||||
|
||||
Controla a base com o firmware `RoboMovel_CNCV3_ESP32_REST` direto pela API REST do ESP32, sem
|
||||
servidor e sem visão computacional. Joystick da esquerda: frente/trás e lateral. Joystick da
|
||||
direita: giro. O firmware aceita um sentido por vez, então vale o eixo mais inclinado.
|
||||
Soltar os joysticks ou tocar em PARAR envia `/stop`; se a rede cair, o robô para sozinho em 0,4 s.
|
||||
|
||||
## Rodar no desktop
|
||||
|
||||
```bash
|
||||
../robomovel-demo-api-app/.venv/bin/python main.py 192.168.0.84
|
||||
```
|
||||
|
||||
O IP e a velocidade máxima ficam salvos no aparelho.
|
||||
|
||||
## Compilar o APK
|
||||
|
||||
```bash
|
||||
./compilar_apk.sh
|
||||
```
|
||||
|
||||
Mesmo processo do `robomovel-demo-api-app` (veja o README de lá). O APK sai em
|
||||
`bin/robomoveljoystick-0.1.0-arm64-v8a-debug.apk`. O ícone é `icon.svg`; o `icon.png` usado no
|
||||
build é gerado com `inkscape icon.svg --export-type=png --export-filename=icon.png -w 512 -h 512`.
|
||||
@@ -0,0 +1,48 @@
|
||||
[app]
|
||||
|
||||
# (str) Título exibido no Android
|
||||
title = RoboMovel Joystick
|
||||
|
||||
# (str) Nome curto do pacote (sem espaços)
|
||||
package.name = robomoveljoystick
|
||||
|
||||
# (str) Domínio/identificador
|
||||
package.domain = org.robomovel
|
||||
|
||||
# (str) Código-fonte
|
||||
source.dir = .
|
||||
source.include_exts = py,png,jpg,jpeg,kv,atlas,json
|
||||
source.exclude_dirs = .venv,.buildozer-venv,__pycache__,bin,.git
|
||||
|
||||
# (str) Versão mostrada no Android
|
||||
version = 0.1.0
|
||||
|
||||
# (list) Dependências Python empacotadas no APK
|
||||
requirements = python3,kivy==2.3.1,pyjnius,certifi
|
||||
|
||||
# (str) Ícone
|
||||
icon.filename = %(source.dir)s/icon.png
|
||||
|
||||
# (str) Retrato, como no desktop
|
||||
orientation = portrait
|
||||
fullscreen = 0
|
||||
|
||||
# (list) Permissões: rede para falar com o servidor
|
||||
android.permissions = INTERNET,ACCESS_NETWORK_STATE
|
||||
|
||||
# (int) API alvo/mínima
|
||||
android.api = 34
|
||||
android.minapi = 24
|
||||
|
||||
# (str) NDK/SDK usados pelo python-for-android
|
||||
android.ndk = 25b
|
||||
android.sdk = 34
|
||||
|
||||
# (list) Arquiteturas (arm64 cobre celulares atuais)
|
||||
android.archs = arm64-v8a
|
||||
|
||||
# (bool) Aceita licenças do SDK automaticamente
|
||||
android.accept_sdk_license = True
|
||||
|
||||
# (str) Filtro de logcat
|
||||
android.logcat_filters = *:S python:D
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env bash
|
||||
# Compila o APK de depuração (arm64-v8a) do app de joystick do RoboMovel (ESP32).
|
||||
#
|
||||
# O script cuida das duas armadilhas do buildozer/python-for-android:
|
||||
#
|
||||
# 1. O recipe do libffi (usado pelo python3) roda autogen.sh/autoreconf e
|
||||
# precisa de autoconf, automake, libtool e libltdl-dev. Se eles não
|
||||
# estiverem no sistema, o script baixa os .deb e extrai uma cópia local
|
||||
# em ~/.local/share/robomovel-build/autotools (não precisa de sudo).
|
||||
# 2. O python-for-android trata os wheels marcados "android" como puros e o
|
||||
# pip do host recusa ("not a supported wheel on this platform"). O patch
|
||||
# p4a-android-wheel.patch corrige isso e também evita o auto-upgrade do
|
||||
# pip do hostpython (que quebrava o venv do build).
|
||||
#
|
||||
# Uso: ./compilar_apk.sh (compila)
|
||||
# ./compilar_apk.sh --limpar (apaga .buildozer e recompila do zero)
|
||||
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
FERR="${XDG_DATA_HOME:-$HOME/.local/share}/robomovel-build"
|
||||
AUTOTOOLS="$FERR/autotools"
|
||||
P4A=".buildozer/android/platform/python-for-android"
|
||||
APK="bin/robomoveljoystick-0.1.0-arm64-v8a-debug.apk"
|
||||
|
||||
# --- 1. autotools locais (só se o sistema não tiver) -----------------------
|
||||
if ! command -v autoreconf >/dev/null 2>&1; then
|
||||
if [ ! -x "$AUTOTOOLS/usr/bin/autoreconf" ]; then
|
||||
echo "==> Baixando autoconf/automake/libtool para $AUTOTOOLS"
|
||||
mkdir -p "$FERR/debs"
|
||||
(cd "$FERR/debs" && apt-get download autoconf automake m4 libtool libltdl-dev)
|
||||
for d in "$FERR"/debs/*.deb; do dpkg-deb -x "$d" "$AUTOTOOLS"; done
|
||||
|
||||
# Os pacotes do Debian gravam /usr/share/... e /usr/bin/... dentro
|
||||
# dos scripts; apontamos tudo para a cópia local.
|
||||
grep -rlI "/usr/share\|/usr/bin/" "$AUTOTOOLS/usr/share" 2>/dev/null |
|
||||
while read -r f; do
|
||||
sed -i -e "s|/usr/share|$AUTOTOOLS/usr/share|g" \
|
||||
-e "s|/usr/bin/autom4te|$AUTOTOOLS/usr/bin/autom4te|g" \
|
||||
-e "s|/usr/bin/autoconf|$AUTOTOOLS/usr/bin/autoconf|g" \
|
||||
-e "s|/usr/bin/autoheader|$AUTOTOOLS/usr/bin/autoheader|g" \
|
||||
-e "s|'/usr/bin/m4'|'$AUTOTOOLS/usr/bin/m4'|g" "$f"
|
||||
done
|
||||
# Idem nos scripts perl de usr/bin, com wrappers que fixam PERL5LIB.
|
||||
for f in autoreconf autoconf autoheader autom4te autoscan autoupdate \
|
||||
ifnames aclocal-1.16 automake-1.16; do
|
||||
[ -f "$AUTOTOOLS/usr/bin/$f" ] || continue
|
||||
mv "$AUTOTOOLS/usr/bin/$f" "$AUTOTOOLS/usr/bin/$f.real"
|
||||
sed -i -e "s|/usr/share|$AUTOTOOLS/usr/share|g" \
|
||||
-e "s|/usr/bin/autom4te|$AUTOTOOLS/usr/bin/autom4te|g" \
|
||||
-e "s|/usr/bin/autoconf|$AUTOTOOLS/usr/bin/autoconf|g" \
|
||||
-e "s|/usr/bin/autoheader|$AUTOTOOLS/usr/bin/autoheader|g" \
|
||||
-e "s|'/usr/bin/m4'|'$AUTOTOOLS/usr/bin/m4'|g" \
|
||||
"$AUTOTOOLS/usr/bin/$f.real"
|
||||
printf '#!/bin/sh\nexport PERL5LIB=%s/usr/share/autoconf:%s/usr/share/automake-1.16\nexec %s/usr/bin/%s.real "$@"\n' \
|
||||
"$AUTOTOOLS" "$AUTOTOOLS" "$AUTOTOOLS" "$f" > "$AUTOTOOLS/usr/bin/$f"
|
||||
chmod +x "$AUTOTOOLS/usr/bin/$f"
|
||||
done
|
||||
(cd "$AUTOTOOLS/usr/bin" && ln -sf automake-1.16 automake && ln -sf aclocal-1.16 aclocal)
|
||||
# libtoolize é shell (não passa pelo laço acima) e também tem /usr/share fixo.
|
||||
sed -i "s|=\"/usr/share|=\"$AUTOTOOLS/usr/share|g" "$AUTOTOOLS/usr/bin/libtoolize"
|
||||
# autom4te.cfg também tem caminho fixo, mas já foi corrigido no laço acima
|
||||
# (fica em usr/share); corrigir de novo duplicaria o prefixo.
|
||||
fi
|
||||
export PATH="$AUTOTOOLS/usr/bin:$PATH"
|
||||
fi
|
||||
|
||||
# --- 2. venv do buildozer --------------------------------------------------
|
||||
if [ ! -x .buildozer-venv/bin/buildozer ]; then
|
||||
echo "==> Criando .buildozer-venv"
|
||||
python3 -m venv .buildozer-venv
|
||||
.buildozer-venv/bin/pip install -q --upgrade pip
|
||||
.buildozer-venv/bin/pip install -q "buildozer==1.6.0"
|
||||
fi
|
||||
export VIRTUAL_ENV="$PWD/.buildozer-venv"
|
||||
export PATH="$VIRTUAL_ENV/bin:$PATH"
|
||||
|
||||
if [ "${1:-}" = "--limpar" ]; then
|
||||
echo "==> Apagando .buildozer (build do zero; demora bastante)"
|
||||
rm -rf .buildozer
|
||||
fi
|
||||
|
||||
# --- 3. patch do python-for-android ---------------------------------------
|
||||
aplicar_patch() {
|
||||
[ -d "$P4A" ] || return 0
|
||||
if grep -q 'android" in filename' "$P4A/pythonforandroid/build.py"; then
|
||||
return 0
|
||||
fi
|
||||
echo "==> Aplicando p4a-android-wheel.patch"
|
||||
if ! git -C "$P4A" apply "$PWD/p4a-android-wheel.patch"; then
|
||||
echo "AVISO: o patch não aplicou (o python-for-android mudou?)." >&2
|
||||
echo " Se o build falhar com 'not a supported wheel', revise o patch." >&2
|
||||
fi
|
||||
}
|
||||
|
||||
# A primeira execução clona o p4a e só então dá para aplicar o patch.
|
||||
aplicar_patch
|
||||
if ! .buildozer-venv/bin/buildozer android debug; then
|
||||
aplicar_patch
|
||||
.buildozer-venv/bin/buildozer android debug
|
||||
fi
|
||||
|
||||
ls -lh "$APK"
|
||||
echo "APK: $PWD/$APK"
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
@@ -0,0 +1,85 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<defs>
|
||||
<linearGradient id="fundo" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#7a55c4"/>
|
||||
<stop offset="1" stop-color="#2a2152"/>
|
||||
</linearGradient>
|
||||
<linearGradient id="corpo" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#3a3f4d"/>
|
||||
<stop offset="1" stop-color="#23262f"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="manche" cx="0.38" cy="0.32" r="0.75">
|
||||
<stop offset="0" stop-color="#ffe08a"/>
|
||||
<stop offset="0.55" stop-color="#f2bf33"/>
|
||||
<stop offset="1" stop-color="#c98d12"/>
|
||||
</radialGradient>
|
||||
<clipPath id="rodaClip">
|
||||
<rect x="-26" y="-48" width="52" height="96" rx="16"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<rect width="512" height="512" rx="112" fill="url(#fundo)"/>
|
||||
|
||||
<!-- rodas mecanum -->
|
||||
<g transform="translate(106 166)">
|
||||
<rect x="-26" y="-48" width="52" height="96" rx="16" fill="#f2bf33"/>
|
||||
<g clip-path="url(#rodaClip)" stroke="#9c6a08" stroke-width="7" stroke-linecap="round">
|
||||
<line x1="-40" y1="-40" x2="40" y2="-80"/>
|
||||
<line x1="-40" y1="-10" x2="40" y2="-50"/>
|
||||
<line x1="-40" y1="20" x2="40" y2="-20"/>
|
||||
<line x1="-40" y1="50" x2="40" y2="10"/>
|
||||
<line x1="-40" y1="80" x2="40" y2="40"/>
|
||||
</g>
|
||||
</g>
|
||||
<g transform="translate(406 166) scale(-1 1)">
|
||||
<rect x="-26" y="-48" width="52" height="96" rx="16" fill="#f2bf33"/>
|
||||
<g clip-path="url(#rodaClip)" stroke="#9c6a08" stroke-width="7" stroke-linecap="round">
|
||||
<line x1="-40" y1="-40" x2="40" y2="-80"/>
|
||||
<line x1="-40" y1="-10" x2="40" y2="-50"/>
|
||||
<line x1="-40" y1="20" x2="40" y2="-20"/>
|
||||
<line x1="-40" y1="50" x2="40" y2="10"/>
|
||||
<line x1="-40" y1="80" x2="40" y2="40"/>
|
||||
</g>
|
||||
</g>
|
||||
<g transform="translate(106 346) scale(-1 1)">
|
||||
<rect x="-26" y="-48" width="52" height="96" rx="16" fill="#f2bf33"/>
|
||||
<g clip-path="url(#rodaClip)" stroke="#9c6a08" stroke-width="7" stroke-linecap="round">
|
||||
<line x1="-40" y1="-40" x2="40" y2="-80"/>
|
||||
<line x1="-40" y1="-10" x2="40" y2="-50"/>
|
||||
<line x1="-40" y1="20" x2="40" y2="-20"/>
|
||||
<line x1="-40" y1="50" x2="40" y2="10"/>
|
||||
<line x1="-40" y1="80" x2="40" y2="40"/>
|
||||
</g>
|
||||
</g>
|
||||
<g transform="translate(406 346)">
|
||||
<rect x="-26" y="-48" width="52" height="96" rx="16" fill="#f2bf33"/>
|
||||
<g clip-path="url(#rodaClip)" stroke="#9c6a08" stroke-width="7" stroke-linecap="round">
|
||||
<line x1="-40" y1="-40" x2="40" y2="-80"/>
|
||||
<line x1="-40" y1="-10" x2="40" y2="-50"/>
|
||||
<line x1="-40" y1="20" x2="40" y2="-20"/>
|
||||
<line x1="-40" y1="50" x2="40" y2="10"/>
|
||||
<line x1="-40" y1="80" x2="40" y2="40"/>
|
||||
</g>
|
||||
</g>
|
||||
|
||||
<!-- chassi -->
|
||||
<rect x="150" y="118" width="212" height="276" rx="44" fill="url(#corpo)" stroke="#11131a" stroke-width="6"/>
|
||||
|
||||
<!-- base do joystick -->
|
||||
<circle cx="256" cy="270" r="84" fill="#171a21"/>
|
||||
<circle cx="256" cy="270" r="84" fill="none" stroke="#5c6270" stroke-width="5"/>
|
||||
<path d="M256 200 l-12 16 h24 z M256 340 l-12 -16 h24 z M186 270 l16 -12 v24 z M326 270 l-16 -12 v24 z" fill="#5c6270"/>
|
||||
|
||||
<!-- manche -->
|
||||
<ellipse cx="256" cy="268" rx="40" ry="12" fill="#000" opacity="0.35"/>
|
||||
<line x1="256" y1="266" x2="256" y2="232" stroke="#8a909c" stroke-width="12" stroke-linecap="round"/>
|
||||
<circle cx="256" cy="226" r="40" fill="url(#manche)" stroke="#7a5208" stroke-width="4"/>
|
||||
<ellipse cx="243" cy="211" rx="14" ry="9" fill="#fff" opacity="0.55"/>
|
||||
|
||||
<!-- Wi-Fi -->
|
||||
<g fill="none" stroke="#ffffff" stroke-linecap="round" opacity="0.92">
|
||||
<path d="M226 160 a42 42 0 0 1 60 0" stroke-width="10"/>
|
||||
<path d="M206 140 a70 70 0 0 1 100 0" stroke-width="10"/>
|
||||
</g>
|
||||
<circle cx="256" cy="176" r="8" fill="#ffffff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,439 @@
|
||||
"""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/<rota>.
|
||||
"""
|
||||
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.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.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"
|
||||
|
||||
|
||||
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 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)
|
||||
|
||||
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()
|
||||
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()
|
||||
|
||||
# ------------------------------------------------------------ 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("moving"):
|
||||
texto = f"Movendo: {d.get('dir')} · {d.get('speed')} passos/s"
|
||||
else:
|
||||
texto = "Parado"
|
||||
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()
|
||||
@@ -0,0 +1,28 @@
|
||||
diff --git a/pythonforandroid/build.py b/pythonforandroid/build.py
|
||||
index d88fdb1f..25b4bba2 100644
|
||||
--- a/pythonforandroid/build.py
|
||||
+++ b/pythonforandroid/build.py
|
||||
@@ -790,7 +790,10 @@ def process_python_modules(ctx, modules, arch):
|
||||
pure_python = True
|
||||
|
||||
if (
|
||||
- filename.endswith(".whl") and not is_wheel_compatible(filename, arch, ctx)
|
||||
+ filename.endswith(".whl") and (
|
||||
+ "android" in filename
|
||||
+ or not is_wheel_compatible(filename, arch, ctx)
|
||||
+ )
|
||||
):
|
||||
any_not_pure_python = True
|
||||
pure_python = False
|
||||
@@ -873,10 +876,7 @@ def run_pymodules_install(ctx, arch, modules, project_dir=None,
|
||||
# Prepare base environment and upgrade pip:
|
||||
base_env = dict(copy.copy(os.environ))
|
||||
base_env["PYTHONPATH"] = ctx.get_site_packages_dir(arch)
|
||||
- info('Upgrade pip to latest version')
|
||||
- shprint(sh.bash, '-c', (
|
||||
- "source venv/bin/activate && pip install -U pip"
|
||||
- ), _env=copy.copy(base_env))
|
||||
+ info('Using the pip bundled with hostpython (no self-upgrade)')
|
||||
|
||||
# Install Cython in case modules need it to build:
|
||||
info('Install Cython in case one of the modules needs it to build')
|
||||
Reference in new issue
Block a user