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

67
.gitignore vendored
View File

@@ -1,62 +1,5 @@
# ---> C .pio
# Prerequisites .vscode/.browse.c_cpp.db*
*.d .vscode/c_cpp_properties.json
.vscode/launch.json
# Object files .vscode/ipch
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf
# ---> esp-idf
# gitignore template for esp-idf, the official development framework for ESP32
# https://github.com/espressif/esp-idf
build/
sdkconfig
sdkconfig.old

10
.vscode/extensions.json vendored Normal file
View File

@@ -0,0 +1,10 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
]
}

37
include/README Normal file
View File

@@ -0,0 +1,37 @@
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the convention is to give header files names that end with `.h'.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html

46
lib/README Normal file
View File

@@ -0,0 +1,46 @@
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into the executable file.
The source code of each library should be placed in a separate directory
("lib/your_library_name/[Code]").
For example, see the structure of the following example libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional. for custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
Example contents of `src/main.c` using Foo and Bar:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
The PlatformIO Library Dependency Finder will find automatically dependent
libraries by scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html

22
platformio.ini Normal file
View File

@@ -0,0 +1,22 @@
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:wemos_d1_mini32]
platform = espressif32
board = wemos_d1_mini32
framework = arduino
monitor_speed = 115200
lib_deps =
tzapu/WiFiManager@^2.0.16-rc.2
ayushsharma82/ElegantOTA@^3.1.0
bblanchon/ArduinoJson@^6.21.3
board_build.filesystem = littlefs

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()
}

11
test/README Normal file
View File

@@ -0,0 +1,11 @@
This directory is intended for PlatformIO Test Runner and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PlatformIO Unit Testing:
- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html