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
@@ -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