5. 4.4 Client HTTP sur ESP32 avec ArduinoJson
La bibliothèque ArduinoJson v7 gère efficacement le JSON sur ESP32 avec une mémoire statique (pas de malloc/free fragile).
; platformio.ini
lib_deps =
bblanchon/ArduinoJson@^7.0.0
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char* ollamaUrl = "http://192.168.0.210:11434/api/generate";
const char* ollamaModel = "qwen2.5:1.5b";
String askLLM(const String& prompt) {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi non connecte !");
return "";
}
HTTPClient http;
http.begin(ollamaUrl);
http.addHeader("Content-Type", "application/json");
http.setTimeout(30000); // 30 secondes pour l'inference LLM
// Build JSON request
JsonDocument reqDoc;
reqDoc["model"] = ollamaModel;
reqDoc["prompt"] = prompt;
reqDoc["stream"] = false;
JsonObject opts = reqDoc["options"].to<JsonObject>();
opts["num_predict"] = 150; // limit tokens to protect ESP32 RAM
opts["temperature"] = 0.7;
String body;
serializeJson(reqDoc, body);
Serial.println("[LLM] Envoi requete...");
unsigned long start = millis();
int code = http.POST(body);
unsigned long elapsed = millis() - start;
String result = "";
if (code == HTTP_CODE_OK) {
String resp = http.getString();
JsonDocument respDoc;
DeserializationError err = deserializeJson(respDoc, resp);
if (!err) {
result = respDoc["response"].as<String>();
Serial.printf("[LLM] Reponse en %lu ms (%d tokens)\n",
elapsed, respDoc["eval_count"].as<int>());
} else {
Serial.printf("[LLM] Erreur JSON: %s\n", err.c_str());
}
} else {
Serial.printf("[LLM] Erreur HTTP: %d\n", code);
}
http.end();
return result;
}