update api urls

This commit is contained in:
oberon 2026-02-11 20:15:54 +01:00
parent 27d080e09a
commit 55f85f8684

105
app.py
View File

@ -30,6 +30,8 @@ advertiser = AdvertiserBTSocket() # ← ohne tracer, wie korrigiert
# Globale Zustände (für Einzelbenutzer / Entwicklung später Session/DB)
current_config = None
current_hub: MouldKing | None = None
current_module = None # Module6_0 oder Module4_0
current_device = None # Device0/1/2 je nach hub_id
def load_configs():
configs = []
@ -160,70 +162,97 @@ def serve_config_file(filename):
@app.route('/api/connect', methods=['POST'])
def api_connect():
global current_hub
global current_hub, current_module, current_device
if current_config is None:
return jsonify({"success": False, "message": "Keine Konfiguration geladen"}), 400
try:
hub_id = int(current_config.get('hub_id', 0))
hub_type = current_config.get('hub_type', '6channel') # '4channel' oder '6channel'
# Falls schon eine Instanz existiert → erstmal sauber trennen
if current_hub is not None:
# Alte Verbindung sauber trennen
if current_device is not None:
try:
current_hub.disconnect() # ← falls diese Methode existiert
except AttributeError:
current_device.Disconnect()
except:
pass
if current_module is not None:
# ggf. Stop vor Disconnect
try:
current_device.Stop()
except:
pass
except Exception as e:
logger.warning(f"Fehler beim Trennen der alten Instanz: {e}")
# Instanz ohne Argumente erstellen
current_hub = MouldKing() # ← KEINE Argumente!
# Hub-ID und andere Einstellungen ggf. nachträglich setzen
# (das muss deine Bibliothek unterstützen teste!)
# MouldKing neu initialisieren
mk = MouldKing()
mk.SetAdvertiser(advertiser)
try:
current_hub.set_hub_id(hub_id) # ← falls diese Methode existiert
except AttributeError:
logger.warning("Keine set_hub_id-Methode → ID wird evtl. anders gesetzt")
mk.SetTracer(tracer)
except:
pass
current_hub.connect() # ← das sollte den Hub in BT-Modus schalten
# Modul holen
if hub_type.lower() in ['6channel', '6']:
current_module = mk.Module6_0()
else:
current_module = mk.Module4_0()
logger.info(f"Erfolgreich verbunden mit Hub-ID {hub_id}")
return jsonify({"success": True, "message": f"Hub {hub_id} verbunden"})
# Device auswählen (hub_id = 0,1,2 → Device0,1,2)
device_attr = f'Device{hub_id}'
if not hasattr(current_module, device_attr):
raise ValueError(f"Hub-ID {hub_id} nicht unterstützt (max 0-2)")
current_device = getattr(current_module, device_attr)
# Verbinden
current_device.Connect()
current_hub = mk # falls später noch gebraucht
logger.info(f"Verbunden: {hub_type} Hub-ID {hub_id}{device_attr}")
return jsonify({"success": True, "message": f"Hub {hub_id} ({hub_type}) verbunden"})
except Exception as e:
logger.exception("Connect-Fehler")
return jsonify({
"success": False,
"message": f"Verbindungsfehler: {str(e)}"
}), 500
return jsonify({"success": False, "message": f"Verbindungsfehler: {str(e)}"}), 500
@app.route('/api/control', methods=['POST'])
def api_control():
global current_hub
if current_hub is None:
global current_device
if current_device is None:
return jsonify({"success": False, "message": "Nicht verbunden"}), 400
try:
data = request.get_json()
port = data['port']
port = data['port'] # 'A', 'B', ...
value = float(data['value'])
# Config-spezifische Anpassungen
channel_config = next((c for c in current_config['channels'] if c['port'] == port), None)
if channel_config:
if channel_config.get('invert', False):
# Port → channelId mappen (A=0, B=1, ...)
channel_map = {'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5}
if isinstance(port, str):
port_upper = port.upper()
if port_upper in channel_map:
channel_id = channel_map[port_upper]
else:
raise ValueError(f"Ungültiger Port: {port}")
else:
channel_id = int(port)
# Config-spezifische Anpassungen (invert, negative_only, on/off-Werte)
ch_cfg = next((c for c in current_config['channels'] if c['port'].upper() == port.upper()), None)
if ch_cfg:
if ch_cfg.get('invert', False):
value = -value
if channel_config.get('negative_only', False) and value >= 0:
if ch_cfg.get('negative_only', False) and value >= 0:
value = -abs(value)
if channel_config['type'] != 'motor':
value = channel_config.get('on_value', 1.0) if value != 0 else channel_config.get('off_value', 0.0)
if ch_cfg['type'] != 'motor':
value = ch_cfg.get('on_value', 1.0) if value != 0 else ch_cfg.get('off_value', 0.0)
# Hier kommt der echte Aufruf
current_hub.set_motor(channel=port, power=value) # ← ← ← Kernaufruf
# Echter Aufruf!
current_device.SetChannel(channel_id, value)
logger.info(f"Steuerung: {port}{value:.2f}")
logger.info(f"SetChannel({channel_id}, {value:.2f}) → Port {port}")
return jsonify({"success": True})
except Exception as e:
@ -233,12 +262,12 @@ def api_control():
@app.route('/api/stop_all', methods=['POST'])
def api_stop_all():
global current_hub
if current_hub is None:
global current_device
if current_device is None:
return jsonify({"success": False, "message": "Nicht verbunden"}), 400
try:
current_hub.stop_all() # ← oder alle Kanäle manuell auf 0 setzen
current_device.Stop() # ← Stoppt alle Kanäle des Devices
logger.info("Alle Kanäle gestoppt")
return jsonify({"success": True})
except Exception as e: