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. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f267d0c127
commit
4b7f23503a
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"
|
chmod +x "$AUTOTOOLS/usr/bin/$f"
|
||||||
done
|
done
|
||||||
(cd "$AUTOTOOLS/usr/bin" && ln -sf automake-1.16 automake && ln -sf aclocal-1.16 aclocal)
|
(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.
|
# 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" \
|
sed -i "s|=\"/usr/share|=\"$AUTOTOOLS/usr/share|g" "$AUTOTOOLS/usr/bin/libtoolize"
|
||||||
"$AUTOTOOLS/usr/share/autoconf/autom4te.cfg"
|
# 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
|
fi
|
||||||
export PATH="$AUTOTOOLS/usr/bin:$PATH"
|
export PATH="$AUTOTOOLS/usr/bin:$PATH"
|
||||||
fi
|
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')
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
|||||||
|
build/
|
||||||
|
redes_padrao.h
|
||||||
|
__pycache__/
|
||||||
@@ -0,0 +1,604 @@
|
|||||||
|
// RoboMovel - base com CNC Shield V3 em Wemos D1 R32 (ESP32), controlada por API REST
|
||||||
|
//
|
||||||
|
// Ao ligar, o robo fica parado e so se move por comando HTTP:
|
||||||
|
// POST /move?dir=frente&speed=400&ms=1000
|
||||||
|
// dir: frente, tras, esquerda, direita, giro_esquerda, giro_direita
|
||||||
|
// speed: passos/s (opcional, padrao 400, limitado a MAX_SPEED)
|
||||||
|
// ms: duracao (opcional, padrao 1000, limitado a MAX_MS)
|
||||||
|
// POST /stop
|
||||||
|
// GET /status
|
||||||
|
//
|
||||||
|
// Redes Wi-Fi (guardadas na flash, ate MAX_NETWORKS):
|
||||||
|
// GET /wifi lista as redes salvas (nunca devolve senhas)
|
||||||
|
// POST /wifi corpo: ssid=NOME&password=SENHA
|
||||||
|
// DELETE /wifi?ssid=NOME
|
||||||
|
// Canal publico: conecta em wss://pipe.ovelha.cloud/ws/robomovel e aceita a mesma API por
|
||||||
|
// https://pipe.ovelha.cloud/c/robomovel/<rota> (ex.: /c/robomovel/status), sem autenticacao.
|
||||||
|
// Descoberta: responde ao texto "ROBOMOVEL?" em UDP 4210 (broadcast) com o JSON do /status.
|
||||||
|
// Atualizacao pela rede (OTA): host robomovel, sem senha (use ./ota.sh).
|
||||||
|
// Os motores param no inicio da gravacao.
|
||||||
|
//
|
||||||
|
// Sem rede disponivel, a placa cria o Wi-Fi "RoboMovel-Setup" (API em 192.168.4.1).
|
||||||
|
// A senha dele e gerada no primeiro boot e aparece no monitor serial (115200).
|
||||||
|
//
|
||||||
|
// Seguranca: todo movimento termina sozinho apos "ms" e tambem se o Wi-Fi cair.
|
||||||
|
//
|
||||||
|
// HARDWARE:
|
||||||
|
// Mantenha o jumper EN/GND: o D8 da shield e o GPIO12 do ESP32, pino que nao
|
||||||
|
// pode estar em HIGH no boot. Por isso este codigo nao usa esse pino.
|
||||||
|
// Eixo A: jumpers A.STEP -> D12 e A.DIR -> D13.
|
||||||
|
//
|
||||||
|
// Rodas: X = traseira dir, Y = dianteira dir, Z = traseira esq, A = dianteira esq.
|
||||||
|
|
||||||
|
#include <WiFi.h>
|
||||||
|
#include <WebServer.h>
|
||||||
|
#include <ESPmDNS.h>
|
||||||
|
#include <Preferences.h>
|
||||||
|
#include <ArduinoOTA.h>
|
||||||
|
#include <WiFiUdp.h>
|
||||||
|
#include <WebSocketsClient.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
#include "soc/gpio_reg.h"
|
||||||
|
|
||||||
|
enum Wheel { FL, FR, RL, RR, WHEELS };
|
||||||
|
|
||||||
|
// GPIOs da D1 R32 na ordem FL, FR, RL, RR -> eixos A, Y, Z, X
|
||||||
|
const uint8_t STEP_PIN[WHEELS] = {19, 25, 17, 26}; // D12, D3, D4, D2
|
||||||
|
const uint8_t DIR_PIN[WHEELS] = {18, 27, 14, 16}; // D13, D6, D7, D5
|
||||||
|
// Motores da direita sao espelhados. Troque aqui se uma roda girar ao contrario.
|
||||||
|
const bool INVERT[WHEELS] = {false, true, false, true};
|
||||||
|
|
||||||
|
const uint32_t DEFAULT_SPEED = 400; // passos/s
|
||||||
|
const uint32_t MIN_SPEED = 100;
|
||||||
|
const uint32_t MAX_SPEED = 1000;
|
||||||
|
const uint32_t DEFAULT_MS = 1000;
|
||||||
|
const uint32_t MAX_MS = 5000;
|
||||||
|
const float START_SPEED = 150.0; // velocidade de partida/parada (passos/s)
|
||||||
|
const float ACCEL = 1500.0; // passos/s^2
|
||||||
|
const uint32_t TICK_HZ = 20000;
|
||||||
|
|
||||||
|
struct Direction { const char *name; int8_t sign[WHEELS]; };
|
||||||
|
const Direction DIRECTIONS[] = {
|
||||||
|
{"frente", { 1, 1, 1, 1}},
|
||||||
|
{"tras", {-1, -1, -1, -1}},
|
||||||
|
{"esquerda", {-1, 1, 1, -1}},
|
||||||
|
{"direita", { 1, -1, -1, 1}},
|
||||||
|
{"giro_esquerda", {-1, 1, -1, 1}},
|
||||||
|
{"giro_direita", { 1, -1, 1, -1}},
|
||||||
|
};
|
||||||
|
const int NUM_DIRECTIONS = sizeof(DIRECTIONS) / sizeof(DIRECTIONS[0]);
|
||||||
|
|
||||||
|
WebServer server(80);
|
||||||
|
hw_timer_t *stepTimer = nullptr;
|
||||||
|
uint32_t stepMask = 0;
|
||||||
|
|
||||||
|
volatile uint32_t stepRate = 0; // passos/s lido pelo ISR
|
||||||
|
|
||||||
|
int appliedDir = -1; // sentido aplicado nos pinos DIR
|
||||||
|
int requestedDir = -1; // sentido pedido pelo ultimo comando
|
||||||
|
float currentSpeed = 0;
|
||||||
|
uint32_t targetSpeed = 0;
|
||||||
|
bool moving = false;
|
||||||
|
unsigned long moveStartMs = 0;
|
||||||
|
uint32_t moveDurationMs = 0;
|
||||||
|
unsigned long lastRampMs = 0;
|
||||||
|
|
||||||
|
// ---- Wi-Fi ----
|
||||||
|
const int MAX_NETWORKS = 5;
|
||||||
|
const char *FW_VERSION = "ota-5";
|
||||||
|
// Redes padrao (SSID e senha), na ordem de tentativa, em redes_padrao.h (fora do git).
|
||||||
|
// Copie redes_padrao.exemplo.h para redes_padrao.h e preencha. Sao recadastradas a cada boot.
|
||||||
|
#include "redes_padrao.h"
|
||||||
|
const char *AP_SSID = "RoboMovel-Setup";
|
||||||
|
const unsigned long ATTEMPT_MS = 12000; // tempo para tentar cada rede
|
||||||
|
const unsigned long RETRY_MS = 30000; // espera apos falhar em todas
|
||||||
|
const unsigned long AP_GRACE_MS = 5000; // mantem o AP apos conectar
|
||||||
|
|
||||||
|
Preferences prefs;
|
||||||
|
String savedSsid[MAX_NETWORKS];
|
||||||
|
String savedPass[MAX_NETWORKS];
|
||||||
|
int networkCount = 0;
|
||||||
|
String apPassword;
|
||||||
|
bool otaReady = false;
|
||||||
|
WiFiUDP descoberta;
|
||||||
|
WebSocketsClient canal; // canal publico pipe.ovelha.cloud
|
||||||
|
const uint16_t PORTA_DESCOBERTA = 4210;
|
||||||
|
bool apOn = false;
|
||||||
|
bool wasConnected = false;
|
||||||
|
bool attempting = false;
|
||||||
|
bool forceAttempt = false;
|
||||||
|
int nextNetwork = 0;
|
||||||
|
unsigned long attemptStartMs = 0;
|
||||||
|
unsigned long nextAttemptMs = 0;
|
||||||
|
unsigned long connectedAtMs = 0;
|
||||||
|
|
||||||
|
bool moveViaSta = false; // comando recebido com a rede normal conectada
|
||||||
|
|
||||||
|
// Acumulador de fase: o pulso sobe em um tick e desce no seguinte (50 us)
|
||||||
|
void IRAM_ATTR onStepTimer() {
|
||||||
|
static uint32_t acc = 0;
|
||||||
|
static bool high = false;
|
||||||
|
acc += stepRate;
|
||||||
|
if (high) {
|
||||||
|
REG_WRITE(GPIO_OUT_W1TC_REG, stepMask);
|
||||||
|
high = false;
|
||||||
|
} else if (acc >= TICK_HZ) {
|
||||||
|
acc -= TICK_HZ;
|
||||||
|
REG_WRITE(GPIO_OUT_W1TS_REG, stepMask);
|
||||||
|
high = true;
|
||||||
|
}
|
||||||
|
if (stepRate == 0) acc = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
void applyDirection(int d) {
|
||||||
|
for (int i = 0; i < WHEELS; i++) {
|
||||||
|
bool forward = DIRECTIONS[d].sign[i] > 0;
|
||||||
|
if (INVERT[i]) forward = !forward;
|
||||||
|
digitalWrite(DIR_PIN[i], forward ? HIGH : LOW);
|
||||||
|
}
|
||||||
|
delayMicroseconds(5);
|
||||||
|
appliedDir = d;
|
||||||
|
}
|
||||||
|
|
||||||
|
void requestStop() {
|
||||||
|
moving = false;
|
||||||
|
targetSpeed = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atualiza a rampa. O sentido so muda com as rodas paradas.
|
||||||
|
void updateMotion() {
|
||||||
|
unsigned long now = millis();
|
||||||
|
unsigned long dt = now - lastRampMs;
|
||||||
|
if (dt < 5) return;
|
||||||
|
lastRampMs = now;
|
||||||
|
|
||||||
|
if (moving && now - moveStartMs >= moveDurationMs) requestStop();
|
||||||
|
if (moving && moveViaSta && WiFi.status() != WL_CONNECTED) requestStop();
|
||||||
|
|
||||||
|
float desired = targetSpeed;
|
||||||
|
if (moving && requestedDir != appliedDir) {
|
||||||
|
if (currentSpeed <= 0) applyDirection(requestedDir);
|
||||||
|
else desired = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
float delta = ACCEL * dt / 1000.0;
|
||||||
|
if (currentSpeed < desired) {
|
||||||
|
currentSpeed = max(currentSpeed + delta, min(START_SPEED, desired));
|
||||||
|
if (currentSpeed > desired) currentSpeed = desired;
|
||||||
|
} else if (currentSpeed > desired) {
|
||||||
|
currentSpeed -= delta;
|
||||||
|
if (currentSpeed < desired) currentSpeed = desired;
|
||||||
|
if (desired == 0 && currentSpeed < START_SPEED) currentSpeed = 0;
|
||||||
|
}
|
||||||
|
stepRate = (uint32_t)currentSpeed;
|
||||||
|
}
|
||||||
|
|
||||||
|
String jsonEscape(const String &in) {
|
||||||
|
String out;
|
||||||
|
for (unsigned int i = 0; i < in.length(); i++) {
|
||||||
|
char c = in[i];
|
||||||
|
if (c == '"' || c == '\\') { out += '\\'; out += c; }
|
||||||
|
else if ((uint8_t)c >= 0x20) out += c;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
String statusJson() {
|
||||||
|
String s = "{\"fw\":\"";
|
||||||
|
s += FW_VERSION;
|
||||||
|
s += "\",\"moving\":";
|
||||||
|
s += moving ? "true" : "false";
|
||||||
|
s += ",\"dir\":\"";
|
||||||
|
s += (moving && requestedDir >= 0) ? DIRECTIONS[requestedDir].name : "parado";
|
||||||
|
s += "\",\"speed\":";
|
||||||
|
s += stepRate;
|
||||||
|
s += ",\"target_speed\":";
|
||||||
|
s += targetSpeed;
|
||||||
|
s += ",\"remaining_ms\":";
|
||||||
|
long remaining = moving ? (long)moveDurationMs - (long)(millis() - moveStartMs) : 0;
|
||||||
|
s += max(remaining, 0L);
|
||||||
|
s += ",\"wifi_connected\":";
|
||||||
|
s += WiFi.status() == WL_CONNECTED ? "true" : "false";
|
||||||
|
s += ",\"ssid\":\"";
|
||||||
|
s += WiFi.status() == WL_CONNECTED ? jsonEscape(WiFi.SSID()) : "";
|
||||||
|
s += "\",\"ip\":\"";
|
||||||
|
s += WiFi.status() == WL_CONNECTED ? WiFi.localIP().toString() : WiFi.softAPIP().toString();
|
||||||
|
s += "\",\"canal\":";
|
||||||
|
s += canal.isConnected() ? "true" : "false";
|
||||||
|
s += ",\"setup_ap\":";
|
||||||
|
s += apOn ? "true" : "false";
|
||||||
|
s += "}";
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Canal pipe.ovelha.cloud ----
|
||||||
|
bool canalIniciado = false;
|
||||||
|
bool viaCanal = false; // true enquanto um pedido vindo do canal esta sendo tratado
|
||||||
|
JsonObject canalQuery;
|
||||||
|
int canalCodigo = 0;
|
||||||
|
String canalCorpo;
|
||||||
|
|
||||||
|
String argv(const char *nome) {
|
||||||
|
if (viaCanal) return canalQuery[nome].isNull() ? String() : canalQuery[nome].as<String>();
|
||||||
|
return server.arg(nome);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool hasArgv(const char *nome) {
|
||||||
|
return viaCanal ? !canalQuery[nome].isNull() : server.hasArg(nome);
|
||||||
|
}
|
||||||
|
|
||||||
|
void responder(int codigo, const char *tipo, const String &corpo) {
|
||||||
|
if (viaCanal) {
|
||||||
|
canalCodigo = codigo;
|
||||||
|
canalCorpo = corpo;
|
||||||
|
} else {
|
||||||
|
server.send(codigo, tipo, corpo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void sendError(int code, const String &msg) {
|
||||||
|
responder(code, "application/json", "{\"error\":\"" + msg + "\"}");
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleMove() {
|
||||||
|
String name = argv("dir");
|
||||||
|
int d = -1;
|
||||||
|
for (int i = 0; i < NUM_DIRECTIONS; i++) {
|
||||||
|
if (name == DIRECTIONS[i].name) d = i;
|
||||||
|
}
|
||||||
|
if (d < 0) {
|
||||||
|
sendError(400, "dir invalido");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
long speed = hasArgv("speed") ? argv("speed").toInt() : DEFAULT_SPEED;
|
||||||
|
long ms = hasArgv("ms") ? argv("ms").toInt() : DEFAULT_MS;
|
||||||
|
if (speed <= 0 || ms <= 0) {
|
||||||
|
sendError(400, "speed e ms precisam ser numeros positivos");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
requestedDir = d;
|
||||||
|
targetSpeed = constrain(speed, (long)MIN_SPEED, (long)MAX_SPEED);
|
||||||
|
moveDurationMs = min((uint32_t)ms, MAX_MS);
|
||||||
|
moveStartMs = millis();
|
||||||
|
moving = true;
|
||||||
|
moveViaSta = WiFi.status() == WL_CONNECTED;
|
||||||
|
responder(200, "application/json", statusJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleStop() {
|
||||||
|
requestStop();
|
||||||
|
responder(200, "application/json", statusJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleStatus() {
|
||||||
|
responder(200, "application/json", statusJson());
|
||||||
|
}
|
||||||
|
|
||||||
|
void saveNetworks() {
|
||||||
|
prefs.putInt("count", networkCount);
|
||||||
|
for (int i = 0; i < MAX_NETWORKS; i++) {
|
||||||
|
String sk = "s" + String(i), pk = "p" + String(i);
|
||||||
|
if (i < networkCount) {
|
||||||
|
prefs.putString(sk.c_str(), savedSsid[i]);
|
||||||
|
prefs.putString(pk.c_str(), savedPass[i]);
|
||||||
|
} else {
|
||||||
|
prefs.remove(sk.c_str());
|
||||||
|
prefs.remove(pk.c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void loadNetworks() {
|
||||||
|
networkCount = constrain(prefs.getInt("count", 0), 0, MAX_NETWORKS);
|
||||||
|
for (int i = 0; i < networkCount; i++) {
|
||||||
|
savedSsid[i] = prefs.getString(("s" + String(i)).c_str(), "");
|
||||||
|
savedPass[i] = prefs.getString(("p" + String(i)).c_str(), "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void addDefaultNetworks() {
|
||||||
|
bool changed = false;
|
||||||
|
for (auto &net : DEFAULT_NETWORKS) {
|
||||||
|
bool found = false;
|
||||||
|
for (int i = 0; i < networkCount; i++) {
|
||||||
|
if (savedSsid[i] == net[0]) found = true;
|
||||||
|
}
|
||||||
|
if (!found && networkCount < MAX_NETWORKS) {
|
||||||
|
savedSsid[networkCount] = net[0];
|
||||||
|
savedPass[networkCount] = net[1];
|
||||||
|
networkCount++;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) saveNetworks();
|
||||||
|
}
|
||||||
|
|
||||||
|
String loadOrCreatePassword(const char *key) {
|
||||||
|
String value = prefs.getString(key, "");
|
||||||
|
if (value.length() < 8) {
|
||||||
|
const char *chars = "abcdefghjkmnpqrstuvwxyz23456789";
|
||||||
|
value = "";
|
||||||
|
for (int i = 0; i < 10; i++) value += chars[esp_random() % 31];
|
||||||
|
prefs.putString(key, value);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A gravacao bloqueia o loop, entao os motores precisam parar aqui mesmo.
|
||||||
|
void haltMotorsForOta() {
|
||||||
|
requestStop();
|
||||||
|
stepRate = 0;
|
||||||
|
currentSpeed = 0;
|
||||||
|
timerStop(stepTimer);
|
||||||
|
REG_WRITE(GPIO_OUT_W1TC_REG, stepMask);
|
||||||
|
}
|
||||||
|
|
||||||
|
void startOta() {
|
||||||
|
ArduinoOTA.setHostname("robomovel");
|
||||||
|
ArduinoOTA.onStart([]() {
|
||||||
|
haltMotorsForOta();
|
||||||
|
Serial.println("OTA: iniciando");
|
||||||
|
});
|
||||||
|
ArduinoOTA.onEnd([]() { Serial.println("OTA: concluido"); });
|
||||||
|
ArduinoOTA.onError([](ota_error_t error) {
|
||||||
|
Serial.printf("OTA: erro %u\n", error);
|
||||||
|
timerStart(stepTimer);
|
||||||
|
});
|
||||||
|
ArduinoOTA.begin();
|
||||||
|
otaReady = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void startSetupAp() {
|
||||||
|
if (apOn) return;
|
||||||
|
WiFi.mode(WIFI_AP_STA);
|
||||||
|
WiFi.softAP(AP_SSID, apPassword.c_str());
|
||||||
|
apOn = true;
|
||||||
|
Serial.print("Rede de configuracao: ");
|
||||||
|
Serial.print(AP_SSID);
|
||||||
|
Serial.print(" | senha: ");
|
||||||
|
Serial.print(apPassword);
|
||||||
|
Serial.print(" | IP: ");
|
||||||
|
Serial.println(WiFi.softAPIP());
|
||||||
|
}
|
||||||
|
|
||||||
|
void stopSetupAp() {
|
||||||
|
if (!apOn) return;
|
||||||
|
WiFi.softAPdisconnect(true);
|
||||||
|
WiFi.mode(WIFI_STA);
|
||||||
|
apOn = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conecta sem bloquear, para a API e os motores continuarem respondendo.
|
||||||
|
void updateWifi() {
|
||||||
|
unsigned long now = millis();
|
||||||
|
|
||||||
|
if (WiFi.status() == WL_CONNECTED) {
|
||||||
|
if (!wasConnected) {
|
||||||
|
wasConnected = true;
|
||||||
|
attempting = false;
|
||||||
|
connectedAtMs = now;
|
||||||
|
Serial.print("Conectado em ");
|
||||||
|
Serial.print(WiFi.SSID());
|
||||||
|
Serial.print(" | IP: ");
|
||||||
|
Serial.println(WiFi.localIP());
|
||||||
|
startOta();
|
||||||
|
iniciarCanal();
|
||||||
|
}
|
||||||
|
if (apOn && now - connectedAtMs >= AP_GRACE_MS) stopSetupAp();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (wasConnected) {
|
||||||
|
wasConnected = false;
|
||||||
|
if (otaReady) ArduinoOTA.end();
|
||||||
|
otaReady = false;
|
||||||
|
Serial.println("Wi-Fi perdido");
|
||||||
|
nextAttemptMs = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (attempting && now - attemptStartMs < ATTEMPT_MS) return;
|
||||||
|
if (attempting) {
|
||||||
|
attempting = false;
|
||||||
|
if (nextNetwork >= networkCount) {
|
||||||
|
nextNetwork = 0;
|
||||||
|
nextAttemptMs = now + RETRY_MS;
|
||||||
|
startSetupAp();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (networkCount == 0) {
|
||||||
|
startSetupAp();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Trocar de canal derrubaria quem esta configurando pelo AP
|
||||||
|
if (!forceAttempt && apOn && WiFi.softAPgetStationNum() > 0) return;
|
||||||
|
if ((long)(now - nextAttemptMs) < 0) return;
|
||||||
|
|
||||||
|
if (nextNetwork >= networkCount) nextNetwork = 0;
|
||||||
|
Serial.print("Tentando ");
|
||||||
|
Serial.println(savedSsid[nextNetwork]);
|
||||||
|
WiFi.begin(savedSsid[nextNetwork].c_str(), savedPass[nextNetwork].c_str());
|
||||||
|
nextNetwork++;
|
||||||
|
forceAttempt = false;
|
||||||
|
attempting = true;
|
||||||
|
attemptStartMs = now;
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleWifiList() {
|
||||||
|
String s = "{\"networks\":[";
|
||||||
|
for (int i = 0; i < networkCount; i++) {
|
||||||
|
if (i) s += ",";
|
||||||
|
s += "\"" + jsonEscape(savedSsid[i]) + "\"";
|
||||||
|
}
|
||||||
|
s += "],\"max\":";
|
||||||
|
s += MAX_NETWORKS;
|
||||||
|
s += ",\"status\":";
|
||||||
|
s += statusJson();
|
||||||
|
s += "}";
|
||||||
|
responder(200, "application/json", s);
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleWifiAdd() {
|
||||||
|
String ssid = argv("ssid");
|
||||||
|
String password = argv("password");
|
||||||
|
if (ssid.length() < 1 || ssid.length() > 32) {
|
||||||
|
sendError(400, "ssid precisa ter de 1 a 32 caracteres");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (password.length() != 0 && (password.length() < 8 || password.length() > 63)) {
|
||||||
|
sendError(400, "password precisa ter de 8 a 63 caracteres, ou ficar vazio em rede aberta");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int index = -1;
|
||||||
|
for (int i = 0; i < networkCount; i++) {
|
||||||
|
if (savedSsid[i] == ssid) index = i;
|
||||||
|
}
|
||||||
|
if (index < 0) {
|
||||||
|
if (networkCount >= MAX_NETWORKS) {
|
||||||
|
sendError(409, "limite de redes atingido, apague uma antes");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
index = networkCount++;
|
||||||
|
}
|
||||||
|
savedSsid[index] = ssid;
|
||||||
|
savedPass[index] = password;
|
||||||
|
saveNetworks();
|
||||||
|
|
||||||
|
responder(202, "application/json", "{\"saved\":\"" + jsonEscape(ssid) + "\",\"message\":\"tentando conectar\"}");
|
||||||
|
|
||||||
|
// Espera 1 s para a resposta sair antes de mudar de rede
|
||||||
|
if (WiFi.status() != WL_CONNECTED) {
|
||||||
|
nextNetwork = index;
|
||||||
|
attempting = false;
|
||||||
|
forceAttempt = true;
|
||||||
|
nextAttemptMs = millis() + 1000;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void handleWifiDelete() {
|
||||||
|
String ssid = argv("ssid");
|
||||||
|
int index = -1;
|
||||||
|
for (int i = 0; i < networkCount; i++) {
|
||||||
|
if (savedSsid[i] == ssid) index = i;
|
||||||
|
}
|
||||||
|
if (index < 0) {
|
||||||
|
sendError(404, "rede nao cadastrada");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (int i = index; i < networkCount - 1; i++) {
|
||||||
|
savedSsid[i] = savedSsid[i + 1];
|
||||||
|
savedPass[i] = savedPass[i + 1];
|
||||||
|
}
|
||||||
|
networkCount--;
|
||||||
|
savedSsid[networkCount] = "";
|
||||||
|
savedPass[networkCount] = "";
|
||||||
|
saveNetworks();
|
||||||
|
nextNetwork = 0;
|
||||||
|
responder(200, "application/json", "{\"deleted\":\"" + jsonEscape(ssid) + "\"}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Responde quem procura o robo na rede (o app manda um broadcast e usa o IP de quem respondeu).
|
||||||
|
void responderDescoberta() {
|
||||||
|
int tamanho = descoberta.parsePacket();
|
||||||
|
if (tamanho <= 0) return;
|
||||||
|
char buf[16] = {0};
|
||||||
|
descoberta.read(buf, sizeof(buf) - 1);
|
||||||
|
if (strncmp(buf, "ROBOMOVEL?", 10) != 0) return;
|
||||||
|
descoberta.beginPacket(descoberta.remoteIP(), descoberta.remotePort());
|
||||||
|
descoberta.print(statusJson());
|
||||||
|
descoberta.endPacket();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pedido HTTP repassado pelo pipe.ovelha.cloud: mesma API, mesma resposta.
|
||||||
|
void tratarCanal(uint8_t *dados, size_t tamanho) {
|
||||||
|
JsonDocument pedido;
|
||||||
|
if (deserializeJson(pedido, dados, tamanho)) return;
|
||||||
|
if (strcmp(pedido["tipo"] | "", "req") != 0) return;
|
||||||
|
String metodo = pedido["method"] | "GET";
|
||||||
|
String rota = pedido["path"] | "/";
|
||||||
|
canalQuery = pedido["query"].as<JsonObject>();
|
||||||
|
viaCanal = true;
|
||||||
|
canalCodigo = 404;
|
||||||
|
canalCorpo = "{\"error\":\"rota nao encontrada\"}";
|
||||||
|
if (rota == "/move" && metodo == "POST") handleMove();
|
||||||
|
else if (rota == "/stop" && metodo == "POST") handleStop();
|
||||||
|
else if (rota == "/status") handleStatus();
|
||||||
|
else if (rota == "/wifi" && metodo == "GET") handleWifiList();
|
||||||
|
else if (rota == "/wifi" && metodo == "POST") handleWifiAdd();
|
||||||
|
else if (rota == "/wifi" && metodo == "DELETE") handleWifiDelete();
|
||||||
|
viaCanal = false;
|
||||||
|
|
||||||
|
JsonDocument resposta;
|
||||||
|
resposta["tipo"] = "resp";
|
||||||
|
resposta["id"] = pedido["id"];
|
||||||
|
resposta["status"] = canalCodigo;
|
||||||
|
resposta["body"] = canalCorpo;
|
||||||
|
String texto;
|
||||||
|
serializeJson(resposta, texto);
|
||||||
|
canal.sendTXT(texto);
|
||||||
|
}
|
||||||
|
|
||||||
|
void iniciarCanal() {
|
||||||
|
if (canalIniciado) return;
|
||||||
|
canal.onEvent([](WStype_t tipo, uint8_t *dados, size_t tamanho) {
|
||||||
|
if (tipo == WStype_TEXT) tratarCanal(dados, tamanho);
|
||||||
|
else if (tipo == WStype_CONNECTED) Serial.println("Canal pipe.ovelha.cloud conectado");
|
||||||
|
else if (tipo == WStype_DISCONNECTED) Serial.println("Canal pipe.ovelha.cloud desconectado");
|
||||||
|
});
|
||||||
|
canal.beginSSL("pipe.ovelha.cloud", 443, "/ws/robomovel");
|
||||||
|
canal.setReconnectInterval(10000);
|
||||||
|
canal.enableHeartbeat(15000, 3000, 2);
|
||||||
|
canalIniciado = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
|
||||||
|
for (int i = 0; i < WHEELS; i++) {
|
||||||
|
pinMode(STEP_PIN[i], OUTPUT);
|
||||||
|
digitalWrite(STEP_PIN[i], LOW);
|
||||||
|
pinMode(DIR_PIN[i], OUTPUT);
|
||||||
|
stepMask |= 1UL << STEP_PIN[i];
|
||||||
|
}
|
||||||
|
applyDirection(0);
|
||||||
|
|
||||||
|
stepTimer = timerBegin(1000000);
|
||||||
|
timerAttachInterrupt(stepTimer, &onStepTimer);
|
||||||
|
timerAlarm(stepTimer, 1000000 / TICK_HZ, true, 0);
|
||||||
|
|
||||||
|
prefs.begin("robomovel", false);
|
||||||
|
loadNetworks();
|
||||||
|
addDefaultNetworks();
|
||||||
|
apPassword = loadOrCreatePassword("ap_pass");
|
||||||
|
Serial.print("Firmware ");
|
||||||
|
Serial.println(FW_VERSION);
|
||||||
|
|
||||||
|
WiFi.persistent(false);
|
||||||
|
WiFi.mode(WIFI_STA);
|
||||||
|
WiFi.setSleep(false);
|
||||||
|
WiFi.setAutoReconnect(false);
|
||||||
|
if (networkCount == 0) startSetupAp();
|
||||||
|
|
||||||
|
server.on("/move", HTTP_POST, handleMove);
|
||||||
|
server.on("/stop", HTTP_POST, handleStop);
|
||||||
|
server.on("/status", HTTP_GET, handleStatus);
|
||||||
|
server.on("/wifi", HTTP_GET, handleWifiList);
|
||||||
|
server.on("/wifi", HTTP_POST, handleWifiAdd);
|
||||||
|
server.on("/wifi", HTTP_DELETE, handleWifiDelete);
|
||||||
|
server.onNotFound([]() { sendError(404, "rota nao encontrada"); });
|
||||||
|
server.begin();
|
||||||
|
descoberta.begin(PORTA_DESCOBERTA);
|
||||||
|
Serial.println("API REST pronta");
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
server.handleClient();
|
||||||
|
updateMotion();
|
||||||
|
updateWifi();
|
||||||
|
if (otaReady) ArduinoOTA.handle();
|
||||||
|
responderDescoberta();
|
||||||
|
if (canalIniciado) canal.loop();
|
||||||
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Compila e grava este sketch no robo pelo Wi-Fi. Uso: ./ota.sh [ip_ou_host]
|
||||||
|
set -e
|
||||||
|
HOST="${1:-robomovel.local}"
|
||||||
|
DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
CLI=/home/marcel/Applications/arduino-ide-2.3.10/resources/app/lib/backend/resources/arduino-cli
|
||||||
|
ESPOTA=$(ls ~/.arduino15/packages/esp32/hardware/esp32/*/tools/espota.py | tail -1)
|
||||||
|
BUILD=$(mktemp -d)
|
||||||
|
trap 'rm -rf "$BUILD"' EXIT
|
||||||
|
"$CLI" compile --fqbn esp32:esp32:d1_uno32 --output-dir "$BUILD" "$DIR"
|
||||||
|
python3 "$ESPOTA" -i "$(getent ahostsv4 "$HOST" | awk '{print $1; exit}')" -f "$BUILD/$(basename "$DIR").ino.bin"
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Painel de teste do RoboMovel. Uso: python3 app.py -> http://127.0.0.1:5000
|
||||||
|
Outro IP: ROBO=192.168.0.84 python3 app.py"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
from flask import Flask, jsonify, render_template_string, request
|
||||||
|
|
||||||
|
ROBO = os.environ.get("ROBO", "192.168.0.84")
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def chamar(metodo, rota, params=None):
|
||||||
|
url = f"http://{ROBO}{rota}"
|
||||||
|
if params:
|
||||||
|
url += "?" + urllib.parse.urlencode(params)
|
||||||
|
req = urllib.request.Request(url, method=metodo)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=4) as r:
|
||||||
|
return jsonify(json.load(r)), r.status
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return jsonify(json.load(e)), e.code
|
||||||
|
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
||||||
|
return jsonify(error=f"robo sem resposta: {e}"), 502
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/move")
|
||||||
|
def mover():
|
||||||
|
return chamar("POST", "/move", {k: request.args[k] for k in ("dir", "speed", "ms") if k in request.args})
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/stop")
|
||||||
|
def parar():
|
||||||
|
return chamar("POST", "/stop")
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/status")
|
||||||
|
def estado():
|
||||||
|
return chamar("GET", "/status")
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/")
|
||||||
|
def pagina():
|
||||||
|
return render_template_string(PAGINA, robo=ROBO)
|
||||||
|
|
||||||
|
|
||||||
|
PAGINA = """<!doctype html>
|
||||||
|
<html lang="pt-BR"><head><meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>RoboMovel</title>
|
||||||
|
<style>
|
||||||
|
:root{color-scheme:light dark;--bg:#f4f5f7;--card:#fff;--tx:#1b1f24;--mut:#667;--btn:#e6e9ee;--ac:#1769e0;--stop:#d92d20}
|
||||||
|
@media (prefers-color-scheme:dark){:root{--bg:#14171b;--card:#1e2329;--tx:#eef1f4;--mut:#9aa5b1;--btn:#2c333b;--ac:#4c93f5}}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
body{margin:0;background:var(--bg);color:var(--tx);font:16px system-ui,sans-serif;padding:16px}
|
||||||
|
main{max-width:420px;margin:auto;background:var(--card);border-radius:14px;padding:20px}
|
||||||
|
h1{font-size:20px;margin:0}
|
||||||
|
small,.mut{color:var(--mut)}
|
||||||
|
.pad{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin:18px 0}
|
||||||
|
button{border:0;border-radius:10px;background:var(--btn);color:var(--tx);font:inherit;font-weight:600;padding:18px 4px;cursor:pointer;min-height:60px}
|
||||||
|
button:active{background:var(--ac);color:#fff}
|
||||||
|
button:disabled{opacity:.5}
|
||||||
|
#parar{width:100%;background:var(--stop);color:#fff;font-size:18px}
|
||||||
|
label{display:block;margin-top:14px}
|
||||||
|
input[type=range]{width:100%}
|
||||||
|
#estado{display:flex;gap:8px;align-items:center;margin-top:16px;font-weight:600}
|
||||||
|
#luz{width:12px;height:12px;border-radius:50%;background:#999}
|
||||||
|
pre{white-space:pre-wrap;word-break:break-word;font-size:13px;color:var(--mut);margin:10px 0 0}
|
||||||
|
</style></head><body><main>
|
||||||
|
<h1>RoboMovel</h1><small>Robô em {{ robo }}</small>
|
||||||
|
<div class="pad">
|
||||||
|
<button data-d="giro_esquerda">↺ Giro<br>esq.</button><button data-d="frente">↑ Frente</button><button data-d="giro_direita">↻ Giro<br>dir.</button>
|
||||||
|
<button data-d="esquerda">← Esq.</button><button data-d="tras">↓ Trás</button><button data-d="direita">→ Dir.</button>
|
||||||
|
</div>
|
||||||
|
<button id="parar">PARAR (espaço)</button>
|
||||||
|
<label>Velocidade: <b id="vs"></b> passos/s<input id="v" type="range" min="100" max="1000" step="50" value="300"></label>
|
||||||
|
<label>Duração: <b id="ts"></b> s<input id="t" type="range" min="100" max="5000" step="100" value="500"></label>
|
||||||
|
<div id="estado"><span id="luz"></span><span id="txt">Conectando…</span></div>
|
||||||
|
<pre id="log"></pre>
|
||||||
|
<p class="mut"><small>Teclado: setas movem, Q e E giram, espaço para.</small></p>
|
||||||
|
</main><script>
|
||||||
|
const $=i=>document.getElementById(i);
|
||||||
|
function campos(){$('vs').textContent=$('v').value;$('ts').textContent=($('t').value/1000).toFixed(1)}
|
||||||
|
$('v').oninput=$('t').oninput=campos;campos();
|
||||||
|
async function api(m,u){
|
||||||
|
try{const r=await fetch(u,{method:m});const d=await r.json();mostra(d);return d}
|
||||||
|
catch(e){mostra({error:'painel sem resposta'})}
|
||||||
|
}
|
||||||
|
function mostra(d){
|
||||||
|
const erro=d.error;
|
||||||
|
$('luz').style.background=erro?'#d92d20':d.moving?'#1769e0':'#12a150';
|
||||||
|
$('txt').textContent=erro?erro:d.moving?('Movendo: '+d.dir+' ('+d.speed+' passos/s)'):'Parado';
|
||||||
|
$('log').textContent=JSON.stringify(d);
|
||||||
|
}
|
||||||
|
function mover(d){api('POST','/api/move?dir='+d+'&speed='+$('v').value+'&ms='+$('t').value)}
|
||||||
|
function parar(){api('POST','/api/stop')}
|
||||||
|
document.querySelectorAll('[data-d]').forEach(b=>b.onclick=()=>mover(b.dataset.d));
|
||||||
|
$('parar').onclick=parar;
|
||||||
|
const teclas={ArrowUp:'frente',ArrowDown:'tras',ArrowLeft:'esquerda',ArrowRight:'direita',q:'giro_esquerda',e:'giro_direita'};
|
||||||
|
addEventListener('keydown',e=>{
|
||||||
|
if(e.repeat)return;
|
||||||
|
if(e.code==='Space'){e.preventDefault();parar();return}
|
||||||
|
const d=teclas[e.key];
|
||||||
|
if(d){e.preventDefault();mover(d)}
|
||||||
|
});
|
||||||
|
setInterval(()=>api('GET','/api/status'),1000);api('GET','/api/status');
|
||||||
|
</script></body></html>"""
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
app.run(host="127.0.0.1", port=5000)
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
// Copie para redes_padrao.h e troque pelos SSIDs e senhas reais (na ordem de tentativa).
|
||||||
|
const char *DEFAULT_NETWORKS[][2] = {
|
||||||
|
{"MINHA_REDE", "minha_senha"},
|
||||||
|
};
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
# Parte que precisa de sudo: site do nginx + certificado. Rode: sudo bash ~/pipe/instalar_root.sh
|
||||||
|
set -e
|
||||||
|
cp "$(dirname "$0")/nginx-pipe.ovelha.cloud" /etc/nginx/sites-available/pipe.ovelha.cloud
|
||||||
|
ln -sf /etc/nginx/sites-available/pipe.ovelha.cloud /etc/nginx/sites-enabled/pipe.ovelha.cloud
|
||||||
|
nginx -t
|
||||||
|
systemctl reload nginx
|
||||||
|
certbot --nginx -d pipe.ovelha.cloud --non-interactive --redirect
|
||||||
|
echo "pronto: https://pipe.ovelha.cloud"
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name pipe.ovelha.cloud;
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:8100;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection $http_connection;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_read_timeout 3600s;
|
||||||
|
proxy_send_timeout 3600s;
|
||||||
|
proxy_buffering off;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=pipe.ovelha.cloud (canal publico)
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
WorkingDirectory=%h/pipe
|
||||||
|
ExecStart=%h/pipe/.venv/bin/python %h/pipe/servidor.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
"""pipe.ovelha.cloud: canal público de comunicação entre projetos (sem autenticação).
|
||||||
|
|
||||||
|
WebSocket /ws/<canal> entra no canal. Mensagens de texto vão para os outros do canal.
|
||||||
|
HTTP /c/<canal>/<rota> vira uma requisição para quem está no canal:
|
||||||
|
-> {"tipo":"req","id":"...","method":"POST","path":"/move","query":{...}}
|
||||||
|
<- {"tipo":"resp","id":"...","status":200,"body":"..."} (o primeiro que responder)
|
||||||
|
GET /canais lista os canais e quantos estão conectados.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from aiohttp import WSMsgType, web
|
||||||
|
|
||||||
|
ESPERA_S = 6
|
||||||
|
canais = {} # canal -> set de WebSocketResponse
|
||||||
|
pendentes = {} # id -> Future
|
||||||
|
|
||||||
|
|
||||||
|
async def ws_canal(request):
|
||||||
|
canal = request.match_info["canal"]
|
||||||
|
ws = web.WebSocketResponse(heartbeat=20)
|
||||||
|
await ws.prepare(request)
|
||||||
|
membros = canais.setdefault(canal, set())
|
||||||
|
membros.add(ws)
|
||||||
|
try:
|
||||||
|
async for msg in ws:
|
||||||
|
if msg.type != WSMsgType.TEXT:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
dado = json.loads(msg.data)
|
||||||
|
except ValueError:
|
||||||
|
dado = None
|
||||||
|
if isinstance(dado, dict) and dado.get("tipo") == "resp":
|
||||||
|
fut = pendentes.get(dado.get("id"))
|
||||||
|
if fut and not fut.done():
|
||||||
|
fut.set_result(dado)
|
||||||
|
continue
|
||||||
|
for outro in list(membros):
|
||||||
|
if outro is not ws and not outro.closed:
|
||||||
|
await outro.send_str(msg.data)
|
||||||
|
finally:
|
||||||
|
membros.discard(ws)
|
||||||
|
if not membros:
|
||||||
|
canais.pop(canal, None)
|
||||||
|
return ws
|
||||||
|
|
||||||
|
|
||||||
|
async def http_canal(request):
|
||||||
|
canal = request.match_info["canal"]
|
||||||
|
membros = [m for m in canais.get(canal, ()) if not m.closed]
|
||||||
|
if not membros:
|
||||||
|
return web.json_response({"error": f"ninguém conectado no canal {canal}"}, status=503)
|
||||||
|
query = dict(request.query)
|
||||||
|
if request.can_read_body and request.content_type == "application/x-www-form-urlencoded":
|
||||||
|
query.update(await request.post())
|
||||||
|
pedido = {"tipo": "req", "id": uuid.uuid4().hex, "method": request.method,
|
||||||
|
"path": "/" + request.match_info["rota"], "query": {k: str(v) for k, v in query.items()}}
|
||||||
|
fut = asyncio.get_running_loop().create_future()
|
||||||
|
pendentes[pedido["id"]] = fut
|
||||||
|
try:
|
||||||
|
texto = json.dumps(pedido)
|
||||||
|
for m in membros:
|
||||||
|
await m.send_str(texto)
|
||||||
|
resp = await asyncio.wait_for(fut, ESPERA_S)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
return web.json_response({"error": "o canal não respondeu a tempo"}, status=504)
|
||||||
|
finally:
|
||||||
|
pendentes.pop(pedido["id"], None)
|
||||||
|
return web.Response(text=str(resp.get("body", "")), status=int(resp.get("status", 200)),
|
||||||
|
content_type="application/json")
|
||||||
|
|
||||||
|
|
||||||
|
async def listar(_request):
|
||||||
|
return web.json_response({c: len(m) for c, m in canais.items()})
|
||||||
|
|
||||||
|
|
||||||
|
async def inicio(_request):
|
||||||
|
return web.Response(text=__doc__, content_type="text/plain", charset="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
app = web.Application()
|
||||||
|
app.add_routes([
|
||||||
|
web.get("/", inicio),
|
||||||
|
web.get("/canais", listar),
|
||||||
|
web.get("/ws/{canal}", ws_canal),
|
||||||
|
web.route("*", "/c/{canal}/{rota:.*}", http_canal),
|
||||||
|
])
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
web.run_app(app, host="127.0.0.1", port=8100)
|
||||||
Reference in new issue
Block a user