app.py:
Code: Alles auswählen
from flask import Flask, render_template, request, redirect, url_for, flash
import os
import subprocess
app = Flask(__name__)
app.secret_key = '1234' # Ändere dies zu einem sicheren Schlüssel
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload():
text = request.form['text']
com_port = request.form['com_port'] # COM-Port vom Formular
# Debug-Print für den COM-Port
print(f'Selected COM-Port: {com_port}')
if not text or not com_port:
flash('Bitte gib einen Text ein und wähle einen COM-Port aus.')
return redirect(url_for('index'))
try:
sketch_path = generate_sketch(text)
compile_and_upload(sketch_path, com_port) # COM-Port sollte korrekt sein
flash('Text erfolgreich hochgeladen!')
except Exception as e:
flash(f'Fehler: {e}')
return redirect(url_for('index'))
def generate_sketch(text):
"""Generiert den Arduino-Sketch und speichert ihn als .ino-Datei."""
sketch_code = f'''
#include <KeyboardDE.h> // Verwende die KeyboardDE-Bibliothek
const char myText[] PROGMEM = R"({text})";
void setup() {{
Keyboard.begin();
delay(5000); // Warte 5 Sekunden, um die Eingabe zu ermöglichen
for (int i = 0; i < sizeof(myText); i++) {{
char ch = pgm_read_byte_near(myText + i);
if (ch == '\\0') break;
Keyboard.write(ch);
}}
Keyboard.end();
}}
void loop() {{
// Kein Code hier benötigt
}}
'''
sketch_path = os.path.join('/home/Flask_app', 'Flask_app.ino')
with open(sketch_path, 'w', encoding='utf-8') as f:
f.write(sketch_code)
return sketch_path
def compile_and_upload(sketch_path, com_port):
"""Kompiliert und lädt den Sketch auf das Arduino hoch."""
arduino_cli_path = '/home/Flask_app/arduino-cli' # Pfad zur Arduino CLI (stelle sicher, dass es ausführbar ist)
# Füge den Pfad zur benutzerdefinierten Bibliothek hinzu
library_path = '/home/Flask_app/KeyboardDE' # Pfad zur KeyboardDE-Bibliothek anpassen
os.environ['ARDUINO_LIBS'] = library_path # Setze die Umgebungsvariable
# Kompilieren
compile_cmd = [arduino_cli_path, 'compile', '--fqbn', 'arduino:avr:micro', '--libraries', library_path, sketch_path]
compile_process = subprocess.run(compile_cmd, capture_output=True, text=True)
if compile_process.returncode != 0:
raise Exception(f"Kompilierung fehlgeschlagen: {compile_process.stderr}")
# Hochladen
upload_cmd = [arduino_cli_path, 'upload', '-p', com_port, '--fqbn', 'arduino:avr:micro', sketch_path]
upload_process = subprocess.run(upload_cmd, capture_output=True, text=True)
if upload_process.returncode != 0:
raise Exception(f"Hochladen fehlgeschlagen: {upload_process.stderr}")
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
Code: Alles auswählen
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arduino Uploader</title>
<script>
let port;
async function connectSerial() {
try {
// Überprüfe, ob die Web Serial API unterstützt wird
if ('serial' in navigator) {
// Fordere den Benutzer auf, einen COM-Port auszuwählen
port = await navigator.serial.requestPort();
// Versuche, den Port zu öffnen
await port.open({ baudRate: 9600 });
// Hole die Port-Informationen
const portInfo = port.getInfo();
// Debugging-Meldung um zu sehen, was wir bekommen
console.log('Port-Info:', portInfo);
// Setze den COM-Port-String manuell
document.getElementById('com_port').value = portInfo.usbProductId; // Setzt die USB-Produkt-ID direkt
alert(`Port ausgewählt: ${portInfo.usbProductId}`);
} else {
alert('Web Serial API wird von diesem Browser nicht unterstützt.');
}
} catch (e) {
alert(`Fehler beim Verbinden mit dem seriellen Port: ${e}`);
}
}
</script>
</head>
<body>
<h1>Arduino Sketch Uploader</h1>
<button id="connect-button" onclick="connectSerial()">Mit COM-Port verbinden</button>
<form action="/upload" method="post">
<label for="text">Text eingeben:</label><br>
<textarea id="text" name="text" rows="10" cols="50"></textarea><br><br>
<label for="com_port">COM-Port:</label><br>
<input type="text" id="com_port" name="com_port" placeholder="Z.B. COM3" required><br><br>
<button type="submit">Hochladen</button>
</form>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</body>
</html>
Habe bereits schon länger nach lösungen gesucht auch mit ChatGTP aber komme auf kein treffer.
Danke und LG
