# main.ino

- Project: [Emo-Desktop-Buddy](https://flashesp.com/explore/exXbPUUr5h8t73TzD4SAA.md) by Xrox
- Board: ESP32C3 Dev Module
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/exXbPUUr5h8t73TzD4SAA/files/ZkZs7DKoeXnXmgAxWprGg

```cpp
/*
 * Projet Emo – OpenRouter (free router) + détection améliorée + anti-null
 * 
 * - Wi-Fi "DESKTOP" (mdp 29620722) pour Internet
 * - Point d'accès "Emo" (mdp 12345678)
 * - Reconnaissance vocale en 2 étapes, mot-clé "emo" avec variantes phonétiques
 * - Envoi 2s après silence, retry automatique si réponse vide
 * - Yeux carrés bleus arrondis, synthèse vocale
 */

#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>

// ---------- CONFIGURATION WI-FI ----------
const char* STA_SSID     = "DESKTOP";
const char* STA_PASSWORD = "29620722";

const char* AP_SSID      = "Emo";
const char* AP_PASSWORD  = "12345678";

// OpenRouter (gratuit)
const char* OPENROUTER_API_KEY = "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";
const char* OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions";
const char* MODEL_NAME = "openrouter/free";  // routeur automatique

WebServer server(80);

// ---------- CONNEXION WI-FI ----------
void setupWiFi() {
  WiFi.softAP(AP_SSID, AP_PASSWORD);
  Serial.print("AP 'Emo', IP : ");
  Serial.println(WiFi.softAPIP());

  Serial.print("Connexion Wi-Fi à ");
  Serial.print(STA_SSID);
  Serial.println(" ...");
  WiFi.begin(STA_SSID, STA_PASSWORD);

  int attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < 40) {
    delay(500);
    Serial.print(".");
    attempts++;
  }

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("\n✅ Connecté !");
  } else {
    Serial.println("\n❌ Échec connexion Wi-Fi.");
  }
}

// ---------- FONCTION QUI APPELLE L'IA (avec retry et parsing solide) ----------
String callOpenRouter(const String& prompt, String& expression) {
  WiFiClientSecure client;
  client.setInsecure();
  client.setTimeout(20);

  HTTPClient http;
  http.begin(client, OPENROUTER_URL);
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Authorization", String("Bearer ") + OPENROUTER_API_KEY);
  http.addHeader("HTTP-Referer", "http://192.168.4.1");
  http.addHeader("X-Title", "Emo Assistant");

  String systemMsg = "Tu es Emo, un assistant vocal amical. Réponds en 2-3 phrases max, en Français. "
                     "Inclus dans ta réponse un champ \"expression\" (happy, sad, angry, surprised, thinking, speaking, neutral). "
                     "Format STRICT : {\"response\":\"...\", \"expression\":\"...\"}. Réponds UNIQUEMENT ce JSON.";

  StaticJsonDocument<1536> doc;
  JsonArray messages = doc.createNestedArray("messages");
  JsonObject sys = messages.createNestedObject();
  sys["role"] = "system";
  sys["content"] = systemMsg;
  JsonObject user = messages.createNestedObject();
  user["role"] = "user";
  user["content"] = prompt;

  doc["model"] = MODEL_NAME;
  doc["temperature"] = 0.7;
  doc["max_tokens"] = 200;

  String requestBody;
  serializeJson(doc, requestBody);

  Serial.print("Requête : ");
  Serial.println(prompt);

  int httpCode = http.POST(requestBody);
  Serial.print("Code HTTP : ");
  Serial.println(httpCode);

  if (httpCode == 200) {
    String response = http.getString();
    http.end();

    StaticJsonDocument<2048> respDoc;
    DeserializationError err = deserializeJson(respDoc, response);
    if (!err) {
      String content = respDoc["choices"][0]["message"]["content"].as<String>();
      content.trim();

      // Essaie de trouver un objet JSON dans la réponse
      int start = content.indexOf('{');
      int end = content.lastIndexOf('}');
      if (start >= 0 && end >= 0) {
        String jsonPart = content.substring(start, end + 1);
        StaticJsonDocument<512> inner;
        if (!deserializeJson(inner, jsonPart)) {
          expression = inner["expression"] | "neutral";
          String resp = inner["response"] | jsonPart;
          if (resp.length() > 0) return resp;
        }
      }

      // Si pas de JSON valide, on utilise le texte brut
      if (content.length() > 0) {
        expression = "neutral";
        return content;
      }
    }
  } else {
    http.end();
  }
  return ""; // Échec
}

// ---------- FONCTION PRINCIPALE AVEC RETRY ----------
String askAI(const String& prompt, String& expression) {
  // 2 tentatives
  for (int i = 0; i < 2; i++) {
    String result = callOpenRouter(prompt, expression);
    if (result.length() > 0) return result;
    delay(1000);
  }

  // Fallback local si l'IA ne répond pas
  expression = "thinking";
  return "Je n'ai pas bien compris, peux-tu répéter autrement ?";
}

// ---------- PAGE WEB (détection "emo" améliorée, silence 2s) ----------
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">
  <title>Emo</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    html, body { width: 100%; height: 100%; background: #000; overflow: hidden; font-family: sans-serif; touch-action: manipulation; }
    .eyes-container { position: absolute; top: 40%; left: 50%; transform: translate(-50%, -50%); display: flex; gap: 15vw; }
    .eye { width: 38vw; height: 38vw; background: #1e90ff; border-radius: 25%; transition: all 0.35s; box-shadow: 0 0 30px rgba(30,144,255,0.6); }
    .eyes-container.happy .eye { transform: scale(0.75); border-radius: 35%; background: #4da6ff; }
    .eyes-container.sad .eye { transform: translateY(15%); border-radius: 20%; background: #3366cc; }
    .eyes-container.angry .eye { background: #ff4d4d; border-radius: 15%; animation: shake 0.3s ease 2; }
    .eyes-container.surprised .eye { transform: scale(1.2); border-radius: 40%; background: #00bfff; }
    .eyes-container.thinking .eye { opacity: 0.7; border-radius: 30%; transform: scale(0.85); }
    .eyes-container.speaking .eye { animation: pulse 0.4s ease 3; }
    @keyframes shake { 0%{transform:translateX(0)}25%{transform:translateX(-5px)}50%{transform:translateX(5px)}75%{transform:translateX(-3px)}100%{transform:translateX(0)} }
    @keyframes pulse { 0%{transform:scale(1)}50%{transform:scale(1.1)}100%{transform:scale(1)} }
    .symbol { position: absolute; top: -25vw; left: 50%; transform: translateX(-50%); font-size: 15vw; color: white; text-shadow: 0 0 20px #1e90ff; opacity: 0; pointer-events: none; transition: opacity 0.3s; }
    .symbol.show { opacity: 1; }
    .debug { position: absolute; bottom: 5%; left: 5%; right: 5%; color: rgba(255,255,255,0.7); font-size: 3.5vw; text-align: center; background: rgba(0,0,0,0.5); padding: 8px; border-radius: 10px; pointer-events: none; z-index: 10; }
  </style>
</head>
<body>
  <div class="eyes-container" id="eyesContainer"><div class="eye"></div><div class="eye"></div><div class="symbol" id="symbol">?</div></div>
  <div class="debug" id="debug"></div>
  <script>
    const eyesContainer = document.getElementById('eyesContainer');
    const symbol = document.getElementById('symbol');
    const debugDiv = document.getElementById('debug');
    let keywordRecognition = null, questionRecognition = null, isListeningForKeyword = false, silenceTimer = null;

    function debug(msg) { debugDiv.textContent = msg; }
    function setExpression(expr) {
      eyesContainer.className = 'eyes-container ' + expr;
      symbol.classList.toggle('show', ['thinking','speaking','surprised'].includes(expr));
      symbol.textContent = (expr === 'thinking') ? '?' : '!';
    }
    function speakText(text) {
      if ('speechSynthesis' in window) {
        window.speechSynthesis.cancel();
        const u = new SpeechSynthesisUtterance(text);
        u.lang = 'fr-FR'; u.rate = 0.9;
        window.speechSynthesis.speak(u);
      }
    }

    async function sendQuestion(text) {
      debug("Envoi : " + text);
      setExpression('speaking');
      try {
        const r = await fetch('/api/ask', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({text:text}) });
        const d = await r.json();
        const resp = d.response || "";
        debug("Réponse : " + resp);
        if (resp.length > 0) speakText(resp);
        if (d.expression) setExpression(d.expression);
        setTimeout(() => { setExpression('neutral'); debug("Dites 'emo'..."); startKeywordListening(); }, 4000);
      } catch(e) {
        setExpression('sad'); debug("Erreur réseau");
        setTimeout(() => { setExpression('neutral'); debug("Dites 'emo'..."); startKeywordListening(); }, 3000);
      }
    }

    function startQuestionListening() {
      if (questionRecognition) questionRecognition.abort();
      const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
      questionRecognition = new SR();
      questionRecognition.continuous = false;
      questionRecognition.interimResults = true;
      questionRecognition.lang = 'fr-FR';
      let finalTranscript = '';
      questionRecognition.onresult = (e) => {
        for (let i = e.resultIndex; i < e.results.length; ++i) if (e.results[i].isFinal) finalTranscript += e.results[i][0].transcript + ' ';
        debug("Question : " + finalTranscript);
        clearTimeout(silenceTimer);
        silenceTimer = setTimeout(() => {
          const q = finalTranscript.trim();
          if (q) sendQuestion(q);
          else { debug("Question vide. Dites 'emo'..."); setExpression('neutral'); startKeywordListening(); }
        }, 2000);  // silence 2 secondes
      };
      questionRecognition.onerror = () => { clearTimeout(silenceTimer); startKeywordListening(); };
      questionRecognition.start();
    }

    // Fonction qui vérifie si le texte contient une variante de "emo"
    function containsEmo(text) {
      const t = text.toLowerCase();
      // Détection phonétique étendue
      const patterns = [
        "emo", "émo", "hémot", "aimant", "émaux", "émot", "émeut", "aimons",
        "émond", "immo", "emo ", " emo", "hémo", "emmo", "èmo", "eemo"
      ];
      for (let p of patterns) {
        if (t.includes(p)) return true;
      }
      // Regex : suite de lettres proches
      return /[eéèê]m[oôau]/.test(t);
    }

    function startKeywordListening() {
      if (keywordRecognition) keywordRecognition.abort();
      const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
      keywordRecognition = new SR();
      keywordRecognition.continuous = true;
      keywordRecognition.interimResults = true;
      keywordRecognition.lang = 'fr-FR';
      keywordRecognition.onresult = (e) => {
        let final = '';
        for (let i = e.resultIndex; i < e.results.length; ++i) if (e.results[i].isFinal) final += e.results[i][0].transcript + ' ';
        debug("Entendu : " + final);
        if (containsEmo(final)) {
          debug("'emo' détecté !");
          keywordRecognition.abort();
          isListeningForKeyword = false;
          setExpression('thinking');
          symbol.classList.add('show');
          startQuestionListening();
        }
      };
      keywordRecognition.onerror = (e) => {
        if (e.error === 'not-allowed') { debug("Micro refusé"); return; }
        setTimeout(() => { if (isListeningForKeyword) try { keywordRecognition.start(); } catch(ex) {} }, 1000);
      };
      keywordRecognition.onend = () => {
        if (isListeningForKeyword) setTimeout(() => { try { keywordRecognition.start(); } catch(ex) {} }, 500);
      };
      keywordRecognition.start();
      isListeningForKeyword = true;
    }

    const startBtn = document.createElement('button');
    startBtn.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;background:transparent;border:none;z-index:9999;cursor:pointer;';
    document.body.appendChild(startBtn);
    startBtn.addEventListener('click', () => {
      if (isListeningForKeyword) return;
      startBtn.remove();
      setExpression('neutral');
      debug("Dites 'emo'...");
      startKeywordListening();
    });
  </script>
</body>
</html>
)rawliteral";

// ---------- ROUTES ----------
void handleRoot() {
  server.send(200, "text/html", index_html);
}

void handleAsk() {
  if (WiFi.status() != WL_CONNECTED) {
    server.send(503, "application/json", "{\"response\":\"Pas de connexion Internet.\",\"expression\":\"sad\"}");
    return;
  }

  String body = server.arg("plain");
  StaticJsonDocument<512> doc;
  if (deserializeJson(doc, body) || !doc.containsKey("text")) {
    server.send(400, "application/json", "{\"response\":\"Requête invalide.\",\"expression\":\"sad\"}");
    return;
  }

  const char* text = doc["text"];
  String expression = "neutral";
  String responseText = askAI(String(text), expression);

  // Si la réponse est vide après retry, on met un message par défaut
  if (responseText.length() == 0) {
    responseText = "Je suis un peu perdu, réessaie.";
    expression = "sad";
  }

  StaticJsonDocument<1024> respDoc;
  respDoc["response"] = responseText;
  respDoc["expression"] = expression;
  String jsonResponse;
  serializeJson(respDoc, jsonResponse);
  server.send(200, "application/json", jsonResponse);
}

// ---------- SETUP ----------
void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("\n--- Emo (détection émo améliorée) ---");
  setupWiFi();

  server.on("/", handleRoot);
  server.on("/api/ask", handleAsk);
  server.begin();
  Serial.print("Interface : http://");
  Serial.println(WiFi.softAPIP());
}

void loop() {
  server.handleClient();
}
```
