This commit is contained in:
Pascal RIGAUD
2026-02-09 07:38:28 +01:00
parent 0d73fb0cd6
commit 1e258f6805
9 changed files with 724 additions and 62 deletions

413
src/lichessboard.cpp Normal file
View File

@@ -0,0 +1,413 @@
#include "lichessboard.h"
LichessBoard::LichessBoard()
{
streaming = false;
lastHeartbeat = 0;
onMoveReceived = nullptr;
onGameStateChanged = nullptr;
}
void LichessBoard::setToken(String token)
{
apiToken = token;
}
void LichessBoard::setMoveCallback(MoveCallback callback)
{
onMoveReceived = callback;
}
void LichessBoard::setGameStateCallback(GameStateCallback callback)
{
onGameStateChanged = callback;
}
bool LichessBoard::streamGame(String gameId)
{
if (streaming)
{
stop();
}
currentGameId = gameId;
client.setInsecure(); // Pour HTTPS sans certificat
Serial.println("Connexion à Lichess...");
if (!client.connect("lichess.org", 443))
{
Serial.println("Échec connexion");
return false;
}
// Requête HTTP pour le stream
String request = "GET /api/board/game/stream/" + gameId + " HTTP/1.1\r\n";
request += "Host: lichess.org\r\n";
if (apiToken.length() > 0)
{
request += "Authorization: Bearer " + apiToken + "\r\n";
}
request += "Accept: application/x-ndjson\r\n";
request += "Connection: keep-alive\r\n";
request += "\r\n";
client.print(request);
Serial.println("Requête envoyée, attente réponse...");
// Attendre les headers HTTP
unsigned long timeout = millis();
while (client.connected() && !client.available())
{
if (millis() - timeout > 5000)
{
Serial.println("Timeout headers");
client.stop();
return false;
}
delay(10);
}
// Lire les headers
bool headersEnded = false;
while (client.available() && !headersEnded)
{
String line = client.readStringUntil('\n');
if (line == "\r" || line.length() == 0)
{
headersEnded = true;
}
Serial.println("Header: " + line);
}
streaming = true;
lastHeartbeat = millis();
Serial.println("Stream démarré!");
return true;
}
bool LichessBoard::streamMyGames()
{
if (apiToken.length() == 0)
{
Serial.println("Token requis pour streamMyGames");
return false;
}
if (streaming)
{
stop();
}
client.setInsecure();
if (!client.connect("lichess.org", 443))
{
Serial.println("Échec connexion");
return false;
}
String request = "GET /api/board/game/stream HTTP/1.1\r\n";
request += "Host: lichess.org\r\n";
request += "Authorization: Bearer " + apiToken + "\r\n";
request += "Accept: application/x-ndjson\r\n";
request += "Connection: keep-alive\r\n";
request += "\r\n";
client.print(request);
// Skip headers
while (client.connected())
{
String line = client.readStringUntil('\n');
if (line == "\r" || line.length() == 0)
break;
}
streaming = true;
lastHeartbeat = millis();
return true;
}
bool LichessBoard::streamEvents()
{
if (apiToken.length() == 0)
{
Serial.println("Token requis");
return false;
}
if (streaming)
{
stop();
}
client.setInsecure();
if (!client.connect("lichess.org", 443))
{
Serial.println("Échec connexion");
return false;
}
String request = "GET /api/stream/event HTTP/1.1\r\n";
request += "Host: lichess.org\r\n";
request += "Authorization: Bearer " + apiToken + "\r\n";
request += "Accept: application/x-ndjson\r\n";
request += "Connection: keep-alive\r\n";
request += "\r\n";
client.print(request);
// Skip headers
while (client.connected())
{
String line = client.readStringUntil('\n');
if (line == "\r" || line.length() == 0)
break;
}
streaming = true;
lastHeartbeat = millis();
return true;
}
void LichessBoard::parseLine(String line)
{
line.trim();
if (line.length() == 0)
{
// Heartbeat (ligne vide)
lastHeartbeat = millis();
return;
}
Serial.println("JSON reçu: " + line);
StaticJsonDocument<256> doc;
DeserializationError error = deserializeJson(doc, line);
if (error)
{
Serial.print("Erreur JSON: ");
Serial.println(error.c_str());
return;
}
// Type d'événement
const char *type = doc["type"];
if (strcmp(type, "gameFull") == 0)
{
// État complet de la partie au début
Serial.println("=== Partie complète reçue ===");
const char *gameId = doc["id"];
const char *state = doc["state"]["status"];
Serial.print("Game ID: ");
Serial.println(gameId);
Serial.print("État: ");
Serial.println(state);
if (onGameStateChanged)
{
onGameStateChanged(String(state));
}
// Récupérer tous les coups déjà joués
const char *moves = doc["state"]["moves"];
if (moves && strlen(moves) > 0)
{
Serial.print("Coups joués: ");
Serial.println(moves);
}
// FEN initial si disponible
const char *initialFen = doc["initialFen"];
if (initialFen)
{
Serial.print("FEN: ");
Serial.println(initialFen);
}
}
else if (strcmp(type, "gameState") == 0)
{
// Mise à jour de l'état (nouveau coup)
Serial.println("=== Nouveau coup ===");
const char *moves = doc["moves"];
const char *status = doc["status"];
Serial.print("Tous les coups: ");
Serial.println(moves);
Serial.print("État: ");
Serial.println(status);
if (onGameStateChanged)
{
onGameStateChanged(String(status));
}
// Extraire le dernier coup
if (moves && strlen(moves) > 0)
{
String allMoves = String(moves);
int lastSpace = allMoves.lastIndexOf(' ');
String lastMove = (lastSpace >= 0) ? allMoves.substring(lastSpace + 1) : allMoves;
// Format UCI: e2e4
if (lastMove.length() >= 4)
{
String from = lastMove.substring(0, 2);
String to = lastMove.substring(2, 4);
Serial.print("Dernier coup: ");
Serial.print(from);
Serial.print(" -> ");
Serial.println(to);
if (onMoveReceived)
{
onMoveReceived(from, to, lastMove, "");
}
}
}
}
else if (strcmp(type, "gameStart") == 0)
{
// Nouvelle partie démarrée
JsonObject game = doc["game"];
const char *gameId = game["id"];
Serial.print("Nouvelle partie: ");
Serial.println(gameId);
if (onGameStateChanged)
{
onGameStateChanged("started");
}
}
else if (strcmp(type, "gameFinish") == 0)
{
// Partie terminée
JsonObject game = doc["game"];
const char *gameId = game["id"];
Serial.print("Partie terminée: ");
Serial.println(gameId);
if (onGameStateChanged)
{
onGameStateChanged("finished");
}
}
}
void LichessBoard::loop()
{
if (!streaming)
{
return;
}
// Vérifier timeout
if (millis() - lastHeartbeat > heartbeatTimeout)
{
Serial.println("Timeout stream!");
stop();
return;
}
// Lire les données disponibles
while (client.available())
{
String line = client.readStringUntil('\n');
parseLine(line);
}
// Vérifier connexion
if (!client.connected())
{
Serial.println("Connexion perdue");
stop();
}
}
void LichessBoard::stop()
{
if (client.connected())
{
client.stop();
}
streaming = false;
currentGameId = "";
Serial.println("Stream arrêté");
}
bool LichessBoard::isStreaming()
{
return streaming;
}
String LichessBoard::getCurrentGameId()
{
return currentGameId;
}
bool LichessBoard::getGameState(String gameId, String &fen, String &lastMove)
{
WiFiClientSecure httpClient;
httpClient.setInsecure();
if (!httpClient.connect("lichess.org", 443))
{
return false;
}
String request = "GET /game/export/" + gameId + "?moves=true&clocks=false HTTP/1.1\r\n";
request += "Host: lichess.org\r\n";
request += "Accept: application/json\r\n";
request += "Connection: close\r\n";
request += "\r\n";
httpClient.print(request);
// Skip headers
while (httpClient.connected())
{
String line = httpClient.readStringUntil('\n');
if (line == "\r")
break;
}
// Lire JSON
String json = httpClient.readString();
httpClient.stop();
StaticJsonDocument<4096> doc;
DeserializationError error = deserializeJson(doc, json);
if (error)
{
return false;
}
const char *moves = doc["moves"];
if (moves)
{
lastMove = String(moves);
// Extraire le dernier coup
int lastSpace = lastMove.lastIndexOf(' ');
if (lastSpace >= 0)
{
lastMove = lastMove.substring(lastSpace + 1);
}
}
return true;
}

59
src/lichessboard.h Normal file
View File

@@ -0,0 +1,59 @@
#ifndef LICHESS_BOARD_H
#define LICHESS_BOARD_H
#include <Arduino.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
// Callback pour chaque coup reçu
typedef void (*MoveCallback)(String from, String to, String san, String fen);
typedef void (*GameStateCallback)(String state); // started, finished, etc.
class LichessBoard
{
private:
WiFiClientSecure client;
String apiToken;
String currentGameId;
bool streaming;
String lastLine;
MoveCallback onMoveReceived;
GameStateCallback onGameStateChanged;
unsigned long lastHeartbeat;
const unsigned long heartbeatTimeout = 10000; // 10 secondes
// Parse une ligne JSON du stream
void parseLine(String line);
public:
LichessBoard();
// Configuration
void setToken(String token);
void setMoveCallback(MoveCallback callback);
void setGameStateCallback(GameStateCallback callback);
// Stream d'une partie spécifique
bool streamGame(String gameId);
// Stream de vos parties en cours (nécessite token)
bool streamMyGames();
// Stream des événements de votre compte
bool streamEvents();
// À appeler dans loop()
void loop();
// Contrôle
void stop();
bool isStreaming();
String getCurrentGameId();
// Récupérer l'état actuel d'une partie (non-stream)
bool getGameState(String gameId, String &fen, String &lastMove);
};
#endif

121
src/main.cpp Normal file
View File

@@ -0,0 +1,121 @@
#include <Arduino.h>
#include <WiFiManager.h>
#include <ElegantOTA.h>
#include <WebServer.h>
#include "LichessBoard.h"
WebServer server(80);
WiFiManager wm;
LichessBoard lichess;
String currentGameId = "";
// Callback quand un coup est joué
void onMove(String from, String to, String san, String fen)
{
Serial.println("\n🎯 NOUVEAU COUP:");
Serial.println(" De: " + from);
Serial.println(" À: " + to);
Serial.println(" Notation: " + san);
// ICI: Allumer des LEDs, bouger des servos, etc.
}
// Callback changement d'état
void onGameState(String state)
{
Serial.println("\n📢 État partie: " + state);
}
void setup()
{
Serial.begin(115200);
// WiFiManager - Portail captif automatique
// Si pas de WiFi configuré, crée un AP "ESP32-Setup"
wm.setConfigPortalTimeout(180); // 3 min timeout
if (!wm.autoConnect("ESP32-Setup", "12345678"))
{
Serial.println("Échec connexion WiFi");
ESP.restart();
}
Serial.println("WiFi connecté!");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
// Configuration Lichess
lichess.setMoveCallback(onMove);
lichess.setGameStateCallback(onGameState);
// OPTIONNEL: Token API pour vos parties privées
// Générer sur: https://lichess.org/account/oauth/token
lichess.setToken("lip_ccje7pt8qzmrVT48d1V8");
// Interface web
server.on("/", []()
{
String html = "<html><head><meta charset='utf-8'><style>";
html += "body{font-family:Arial;max-width:600px;margin:50px auto;padding:20px;}";
html += "input{width:100%;padding:10px;margin:10px 0;font-size:16px;}";
html += "button{width:100%;padding:15px;font-size:18px;background:#4CAF50;color:white;border:none;cursor:pointer;}";
html += "button:hover{background:#45a049;}";
html += ".status{background:#f0f0f0;padding:15px;margin:10px 0;border-radius:5px;}";
html += "</style></head><body>";
html += "<h1>🎮 ESP32 Lichess Board</h1>";
if (lichess.isStreaming()) {
html += "<div class='status'>✅ Stream actif: " + lichess.getCurrentGameId() + "</div>";
html += "<button onclick='location.href=\"/stop\"'>⏹️ Arrêter</button>";
} else {
html += "<div class='status'>⭕ Aucun stream actif</div>";
html += "<form action='/stream' method='POST'>";
html += "<input name='gameid' placeholder='ID de partie (ex: abc12345)' required>";
html += "<button type='submit'>▶️ Démarrer Stream</button>";
html += "</form>";
}
html += "<hr><p>Exemples d'ID:</p>";
html += "<ul><li>Partie TV Lichess: https://lichess.org/<b>abc12345</b></li></ul>";
html += "<a href='/update'>🔄 OTA Update</a>";
html += "</body></html>";
server.send(200, "text/html", html); });
server.on("/stream", HTTP_POST, []()
{
if (server.hasArg("gameid")) {
currentGameId = server.arg("gameid");
currentGameId.trim();
if (lichess.streamGame(currentGameId)) {
server.sendHeader("Location", "/");
server.send(303);
} else {
server.send(500, "text/plain", "Erreur démarrage stream");
}
} else {
server.send(400, "text/plain", "ID manquant");
} });
server.on("/stop", []()
{
lichess.stop();
server.sendHeader("Location", "/");
server.send(303); });
// ElegantOTA - Interface web élégante pour OTA
ElegantOTA.begin(&server);
server.begin();
Serial.println("HTTP server + OTA démarrés");
Serial.println("Ouvrez: http://" + WiFi.localIP().toString());
lichess.streamMyGames();
}
void loop()
{
server.handleClient();
ElegantOTA.loop();
lichess.loop(); // ⚠️ IMPORTANT: appeler dans loop()
}