commit 496a68d63134c37d797390f178e9a3b1e8501448 Author: lucas Date: Mon Jul 29 16:00:55 2024 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..382c44a --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +**/.pio +**/.vscode +**/__pycache__ +**/myenv \ No newline at end of file diff --git a/ESP8266/.gitignore b/ESP8266/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/ESP8266/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/ESP8266/include/README b/ESP8266/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/ESP8266/include/README @@ -0,0 +1,39 @@ + +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 usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +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 diff --git a/ESP8266/lib/README b/ESP8266/lib/README new file mode 100644 index 0000000..2593a33 --- /dev/null +++ b/ESP8266/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, 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 + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/ESP8266/platformio.ini b/ESP8266/platformio.ini new file mode 100644 index 0000000..1bf2dc6 --- /dev/null +++ b/ESP8266/platformio.ini @@ -0,0 +1,17 @@ +; 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:d1_mini] +platform = espressif8266 +board = d1_mini +framework = arduino +monitor_speed = 115200 + +upload_protocol = esptool diff --git a/ESP8266/src/main.cpp b/ESP8266/src/main.cpp new file mode 100644 index 0000000..1bd2792 --- /dev/null +++ b/ESP8266/src/main.cpp @@ -0,0 +1,65 @@ +#include +#include + +// Remplacez par les informations de votre réseau WiFi +const char* ssid = "Le chateau de Chantenay"; +const char* password = "crevette4ever"; + +// Adresse du serveur HTTP sur le PC +const char* host = "192.168.1.62"; // Remplacez par l'adresse IP de votre PC +const int port = 5000; + +const int buttonPin = D7; // Définir le pin du bouton +bool lastButtonState = HIGH; // État précédent du bouton +unsigned long lastDebounceTime = 0; // Dernier temps de changement d'état +unsigned long debounceDelay = 50; // Délai de débounce (en millisecondes) + +void setup() { + Serial.begin(115200); + delay(10); + + pinMode(buttonPin, INPUT_PULLUP); + + WiFi.begin(ssid, password); + Serial.print("Connexion à "); + Serial.print(ssid); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(" connectée"); +} + +void loop() { + int buttonState = digitalRead(buttonPin); // Lire l'état du bouton + + // Vérifier le débounce + if (buttonState != lastButtonState) { + lastDebounceTime = millis(); // Réinitialiser le temps de débounce + } + + // Si l'état du bouton a changé et que le temps de débounce est passé + if ((millis() - lastDebounceTime) > debounceDelay) { + // Si le bouton est pressé (état LOW) + if (buttonState == LOW) { + Serial.println("Bouton pressé! Envoi de la requête..."); + WiFiClient client; + if (client.connect(host, port)) { + client.print(String("GET /execute?box_id=1 HTTP/1.1\r\n") + + "Host: " + host + "\r\n" + + "Connection: close\r\n\r\n"); + + // Attendre et lire la réponse + while (client.available()) { + String line = client.readStringUntil('\r'); + Serial.print(line); + } + client.stop(); + } else { + Serial.println("Échec de la connexion au serveur."); + } + } + } + + lastButtonState = buttonState; // Enregistrer l'état actuel du bouton +} diff --git a/ESP8266/test/README b/ESP8266/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/ESP8266/test/README @@ -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 diff --git a/ESP8266/test/buzzer.cpp b/ESP8266/test/buzzer.cpp new file mode 100644 index 0000000..a4adb7e --- /dev/null +++ b/ESP8266/test/buzzer.cpp @@ -0,0 +1,49 @@ +#include +#include + +// Remplacez par les informations de votre réseau WiFi +const char* ssid = "Le chateau de Chantenay"; +const char* password = "crevette4ever"; + +// Adresse du serveur HTTP sur le PC +const char* host = "192.168.1.62"; // Remplacez par l'adresse IP de votre PC +const int port = 5000; + +const int buttonPin = D7; // Définir le pin du bouton + +void setup() { + Serial.begin(115200); + delay(10); + + pinMode(buttonPin, INPUT_PULLUP); + + WiFi.begin(ssid, password); + Serial.print("Connexion à "); + Serial.print(ssid); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(" connectée"); +} + +void loop() { + if (digitalRead(buttonPin) == HIGH) { // Si le bouton est pressé + Serial.println("Bouton pressé! Envoi de la requête..."); + WiFiClient client; + if (client.connect(host, port)) { + client.print(String("GET /execute HTTP/1.1\r\n") + + "Host: " + host + "\r\n" + + "Connection: close\r\n\r\n"); + delay(500); // Attendre la réponse + while (client.available()) { + String line = client.readStringUntil('\r'); + Serial.print(line); + } + client.stop(); + } else { + Serial.println("Échec de la connexion au serveur."); + } + } + delay(100); // Attendre un peu avant de vérifier à nouveau +} \ No newline at end of file diff --git a/ESP8266/test/main_new.cpp b/ESP8266/test/main_new.cpp new file mode 100644 index 0000000..cafe0d1 --- /dev/null +++ b/ESP8266/test/main_new.cpp @@ -0,0 +1,90 @@ +#include +#include + +// Remplacez par les informations de votre réseau WiFi +const char* ssid = "Le chateau de Chantenay"; +const char* password = "crevette4ever"; + +// Adresse du serveur HTTP sur le PC +const char* host = "192.168.1.62"; // Remplacez par l'adresse IP de votre PC +const int port = 5000; + +const int buttonPin = D7; // Définir le pin du bouton +const int ledPin = D5; // Définir le pin de la LED + +// Variables pour la gestion de l'état du jeu +bool gameActive = false; + +void setup() { + Serial.begin(115200); + delay(10); + + pinMode(buttonPin, INPUT_PULLUP); + pinMode(ledPin, OUTPUT); + digitalWrite(ledPin, LOW); // Éteindre la LED au démarrage + + WiFi.begin(ssid, password); + Serial.print("Connexion à "); + Serial.print(ssid); + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + Serial.println(" connectée"); +} + +void loop() { + // Lire l'état du bouton + if (digitalRead(buttonPin) == HIGH) { // Si le bouton est pressé + Serial.println("Bouton pressé! Envoi de la requête..."); + sendRequest(); + delay(500); // Attendre la réponse + } + + // Vérifier si le jeu est actif + if (gameActive) { + // Clignoter la LED pendant que le jeu est actif + digitalWrite(ledPin, HIGH); + delay(250); + digitalWrite(ledPin, LOW); + delay(250); + } +} + +void sendRequest() { + WiFiClient client; + if (client.connect(host, port)) { + client.print(String("GET /execute?box_id=1 HTTP/1.1\r\n") + + "Host: " + host + "\r\n" + + "Connection: close\r\n\r\n"); + + while (client.available()) { + String line = client.readStringUntil('\r'); + Serial.print(line); + // Gérer les messages reçus pour changer l'état de la LED + if (line.indexOf("fastest") >= 0) { + // Allumer la LED si le message "fastest" est reçu + digitalWrite(ledPin, HIGH); + gameActive = false; // Arrêter le clignotement + } else if (line.indexOf("second") >= 0) { + // Éteindre la LED si le message "second" est reçu + digitalWrite(ledPin, LOW); + } else if (line.indexOf("game_active") >= 0) { + // Si le jeu est actif, activer le clignotement + gameActive = true; + } else if (line.indexOf("reset_game") >= 0) { + // Réinitialiser le jeu et faire clignoter la LED + gameActive = false; // Arrêter le clignotement + for (int i = 0; i < 5; i++) { // Clignoter 5 fois pour signaler la réinitialisation + digitalWrite(ledPin, HIGH); + delay(250); + digitalWrite(ledPin, LOW); + delay(250); + } + } + } + client.stop(); + } else { + Serial.println("Échec de la connexion au serveur."); + } +} \ No newline at end of file diff --git a/ESP8266/test/testBouton.cpp b/ESP8266/test/testBouton.cpp new file mode 100644 index 0000000..c073ace --- /dev/null +++ b/ESP8266/test/testBouton.cpp @@ -0,0 +1,53 @@ +#include + +// Définir les pins +const int buttonPin = D1; // Pin du bouton +const int ledPin = LED_BUILTIN; // Pin de la LED intégrée (D4 sur la plupart des cartes ESP8266) + +// Variables pour suivre l'état du bouton et de la LED +bool ledState = LOW; // État initial de la LED +bool lastButtonState = HIGH; // Dernier état du bouton +unsigned long lastDebounceTime = 0; // Dernière fois que l'état du bouton a changé +unsigned long debounceDelay = 50; // Temps de debounce pour éviter les rebonds du bouton + +void setup() { + // Initialiser la communication série + Serial.begin(115200); + + // Initialiser les pins + pinMode(buttonPin, INPUT_PULLUP); // Pin du bouton en entrée avec pull-up interne + pinMode(ledPin, OUTPUT); // Pin de la LED en sortie + + // Assurer que la LED est éteinte au démarrage + digitalWrite(ledPin, LOW); +} + +void loop() { + // Lire l'état du bouton + int buttonState = digitalRead(buttonPin); + + // Vérifier si l'état du bouton a changé depuis la dernière lecture + if (buttonState != lastButtonState) { + lastDebounceTime = millis(); // Réinitialiser le temps de debounce + } + + // Si le bouton a été maintenu dans le nouvel état assez longtemps + if ((millis() - lastDebounceTime) > debounceDelay) { + // Si le bouton est maintenant pressé (état bas car pin est en pull-up) + if (buttonState == LOW && lastButtonState == HIGH) { + // Inverser l'état de la LED + ledState = !ledState; + digitalWrite(ledPin, ledState); // Mettre à jour l'état de la LED + + // Afficher l'état de la LED sur le moniteur série + if (ledState == HIGH) { + Serial.println("LED allumée"); + } else { + Serial.println("LED éteinte"); + } + } + } + + // Sauvegarder l'état du bouton pour la prochaine lecture + lastButtonState = buttonState; +} \ No newline at end of file diff --git a/Python/buttons.json b/Python/buttons.json new file mode 100644 index 0000000..c89de26 --- /dev/null +++ b/Python/buttons.json @@ -0,0 +1 @@ +{"1": "192.168.1.34", "2": "192.168.1.42"} \ No newline at end of file diff --git a/Python/register.py b/Python/register.py new file mode 100644 index 0000000..1b930c3 --- /dev/null +++ b/Python/register.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python + +from flask import Flask, request, jsonify +import json +import threading +import os +from waitress import serve + +app = Flask(__name__) + +buttons = {} # Dictionnaire pour stocker les boutons et leurs IP +lock = threading.Lock() +EXPECTED_BUTTONS = 2 # Nombre de boutons attendus + +# Fichier pour enregistrer la correspondance +BUTTONS_FILE = 'buttons.json' + +# Compteur pour attribuer un ID unique à chaque bouton +button_counter = 1 + +@app.route('/execute') +def execute_script(): + global buttons, button_counter + ip_address = request.remote_addr # Obtenir l'adresse IP du client + + # Vérifier si l'adresse IP est déjà enregistrée + for button_id, registered_ip in buttons.items(): + if registered_ip == ip_address: + return jsonify({"message": f"Button already registered with ID {button_id}."}), 400 + + with lock: + # Enregistrer le bouton avec son IP si ce n'est pas déjà fait + if len(buttons) < EXPECTED_BUTTONS: + # Attribuer un ID basé sur le compteur + button_id = button_counter + buttons[button_id] = ip_address + print(f"Button {button_id} registered from IP: {ip_address}") + + # Incrémenter le compteur pour le prochain bouton + button_counter += 1 + + # Enregistrer dans le fichier + with open(BUTTONS_FILE, 'w') as f: + json.dump(buttons, f) + + # Vérifier si tous les boutons sont enregistrés + if len(buttons) == EXPECTED_BUTTONS: + print("Tous les boutons sont enregistrés. Prêt à commencer le jeu.") + # Fermer le serveur après enregistrement + os._exit(0) # Quitte le programme + + return jsonify({"message": f"Button {button_id} registered."}), 200 + +if __name__ == '__main__': + print("Serveur d'enregistrement démarré") + serve(app, host='0.0.0.0', port=5000) # Utiliser Waitress pour démarrer le serveur diff --git a/Python/server.py b/Python/server.py new file mode 100644 index 0000000..a83b7de --- /dev/null +++ b/Python/server.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python + +from flask import Flask, request, jsonify +from vlc_control import send_vlc_command +import threading +import keyboard +import json +import os +from waitress import serve +import time + +app = Flask(__name__) + +DEBUG = False + +# Variables globales +fastest = None +lock = threading.Lock() +order = [] # Liste pour suivre l'ordre des boutons +button_ips = {} # Dictionnaire pour enregistrer les adresses IP des boutons +json_file = 'buttons.json' + +# Charger les boutons depuis le fichier JSON s'il existe +if os.path.exists(json_file): + with open(json_file, 'r') as f: + button_ips = json.load(f) + +@app.route('/execute') +def execute_script(): + global fastest + client_ip = request.remote_addr # Obtenir l'adresse IP du client + + # Vérifier si l'adresse IP est enregistrée + button_id = None + for button, ip in button_ips.items(): + if ip == client_ip: + button_id = button + break + + if button_id is None: # Si l'IP n'est pas trouvée + error_message = {"message": "Erreur : cette adresse IP n'est pas enregistrée."} + print(f"{error_message['message']} - IP: {client_ip}") + return jsonify(error_message), 400 # Retourne un code d'erreur 400 + + send_vlc_command('pl_pause', True) # Mettre VLC en pause + + # Utiliser un verrou pour gérer les accès concurrents + with lock: + if button_id not in order: + order.append(button_id) # Ajouter le boîtier à la liste d'ordre + print(f"Boîtiers en ordre: {order}") + if fastest is None: + fastest = button_id # Le premier à arriver devient le gagnant + response_message = {"message": "fastest"} + # print(f"Fastest is {button_id}") + else: + response_message = {"message": "second"} + # print(f"{button_id} is second") + else: + response_message = {"message": "duplicate"} # Requête répétée, rejetée + + return jsonify(response_message), 200 + +def good_answer(): + while True: + # Attendre que la touche 'r' soit pressée pour vider l'ordre + keyboard.wait('o') + with lock: + fastest = None # Réinitialiser le gagnant + if order: + print(f"--- Boîtier {order[0]} gagne ! ---") + order.clear() # Enlever le premier boîtier de l'ordre + #seek_to_time('') + send_vlc_command('pl_play') + +def incomplet_answer(): + global fastest + while True: + # Attendre que la touche 'r' soit pressée pour vider l'ordre + keyboard.wait('x') + with lock: + fastest = None # Réinitialiser le gagnant + if order: + print(f"Boîtier {order[0]} : Réponse incomplète") + order.pop(0) # Enlever le premier boîtier de l'ordre + print(f"Boîtiers en ordre: {order}") + if not order: + send_vlc_command('pl_play') + +def no_answer(): + global fastest + while True: + # Attendre que la touche 'r' soit pressée pour vider l'ordre + keyboard.wait('p') + + with lock: + fastest = None # Réinitialiser le gagnant + if order: + print(f"Boîtier {order[0]} : Pas de réponse") + order.pop(0) # Enlever le premier boîtier de l'ordre + print(f"Boîtiers en ordre: {order}") + if not order: + send_vlc_command('pl_play') + +def next_song(): + global fastest + while True: + # Attendre que la touche 'r' soit pressée pour vider l'ordre + keyboard.wait('n') + print("Are you sure to next ?") + keyboard.wait('n') + with lock: + fastest = None # Réinitialiser le gagnant + if order: + order.pop(0) # Enlever le premier boîtier de l'ordre + print('Next song') + send_vlc_command('pl_next') + +def pause(): + while True: + # Attendre que la touche 'r' soit pressée pour vider l'ordre + keyboard.wait('space') + send_vlc_command('pl_pause', True) + +if __name__ == '__main__': + print("Serveur démarré") + threading.Thread(target=good_answer, daemon=True).start() + threading.Thread(target=incomplet_answer, daemon=True).start() + threading.Thread(target=no_answer, daemon=True).start() + threading.Thread(target=next_song, daemon=True).start() + threading.Thread(target=pause, daemon=True).start() + + serve(app, host='0.0.0.0', port=5000) diff --git a/Python/vlc_control.py b/Python/vlc_control.py new file mode 100644 index 0000000..1b35d17 --- /dev/null +++ b/Python/vlc_control.py @@ -0,0 +1,51 @@ +import requests + +# Configurer l'adresse et le port de l'interface Web de VLC +VLC_WEB_URL = 'http://localhost:8080' +VLC_PASSWORD = 'kiki' # Remplacez ceci par le mot de passe configuré dans l'interface Web +DEBUG = False + +def is_vlc_running(): + try: + response = requests.get(f'{VLC_WEB_URL}/requests/status.json', auth=('', VLC_PASSWORD)) + response.raise_for_status() + return True + except requests.RequestException: + return False + +def get_vlc_status(): + try: + response = requests.get(f'{VLC_WEB_URL}/requests/status.json', auth=('', VLC_PASSWORD)) + response.raise_for_status() + return response.json() + except requests.RequestException as e: + print(f"Erreur lors de la récupération de l'état de VLC : {e}") + return None + +def send_vlc_command(command, check_playing=False): + if not is_vlc_running(): + print(f"VLC n'est pas accessible à {VLC_WEB_URL}. Assurez-vous que VLC est ouvert et que l'interface Web est activée.") + return + + if check_playing: + status = get_vlc_status() + if status is not None: + state = status.get('state') + if state != 'playing': + if DEBUG: + print(f"La commande '{command}' n'est pas nécessaire. État actuel : {state}") + return + try: + response = requests.get(f'{VLC_WEB_URL}/requests/status.json?command={command}', auth=('', VLC_PASSWORD)) + response.raise_for_status() + if DEBUG: + print(f"Commande '{command}' envoyée à VLC.") + except requests.RequestException as e: + if DEBUG: + print(f"Erreur lors de l'envoi de la commande '{command}' à VLC : {e}") + +def seek_to_time(minutes, seconds): + # Convertir le temps en secondes + total_seconds = minutes * 60 + seconds + send_vlc_command(f'seek&val={total_seconds}') + \ No newline at end of file