Spaces:
Build error
Build error
Download app.py from joz88/anycoder-330aebc0: direct link, hf CLI and curl.
- Browser
- Download file 39.1 kB
-
https://huggingface.co/spaces/joz88/anycoder-330aebc0/resolve/main/app.py
- Command line
-
hf download hf://spaces/joz88/anycoder-330aebc0/app.py
-
curl -L -o app.py https://huggingface.co/spaces/joz88/anycoder-330aebc0/resolve/main/app.py
39.1 kB
| import gradio as gr | |
| import json | |
| import time | |
| import random | |
| import hashlib | |
| import datetime | |
| from dataclasses import dataclass, field, asdict | |
| from typing import Optional, List, Dict, Any, Callable | |
| from enum import Enum | |
| # ============================================================ | |
| # ENUMS & DATA MODELS | |
| # ============================================================ | |
| class ConnectionType(Enum): | |
| UART = "uart" | |
| USB = "usb" | |
| BLE = "ble" | |
| WIFI = "wifi" | |
| CAN = "can" | |
| NFC = "nfc" | |
| class ConnectionState(Enum): | |
| DISCONNECTED = "disconnected" | |
| CONNECTING = "connecting" | |
| CONNECTED = "connected" | |
| AUTHENTICATING = "authenticating" | |
| AUTHENTICATED = "authenticated" | |
| ERROR = "error" | |
| class SafetyIntegrityLevel(Enum): | |
| NONE = 0 | |
| SIL1 = 1 | |
| SIL2 = 2 | |
| SIL3 = 3 | |
| SIL4 = 4 | |
| class ResetLevel(Enum): | |
| SOFT = "soft" | |
| STANDARD = "standard" | |
| HARD = "hard" | |
| FACTORY = "factory" | |
| class NfcTagType(Enum): | |
| MIFARE_CLASSIC = "MifareClassic" | |
| MIFARE_DESFIRE = "MifareDESFire" | |
| NTAG215 = "NTAG215" | |
| NTAG216 = "NTAG216" | |
| class DataSourcePriority(Enum): | |
| USB_HARDWARE = "usb_hardware" | |
| NATIVE_BLE = "native_ble" | |
| class HardwareToken: | |
| token_id: str | |
| hardware_id: str | |
| device_id: str | |
| issued_at: str | |
| expires_at: str | |
| permissions: List[str] | |
| sil_level: int = 1 | |
| def is_valid(self) -> bool: | |
| try: | |
| return datetime.datetime.fromisoformat(self.expires_at) > datetime.datetime.now() | |
| except Exception: | |
| return False | |
| def has_permission(self, perm: str) -> bool: | |
| return perm in self.permissions | |
| class McpTool: | |
| id: str | |
| name: str | |
| description: str | |
| category: str | |
| icon: str = "🔧" | |
| execute_fn: Optional[Callable] = None | |
| def execute(self) -> str: | |
| if self.execute_fn: | |
| return self.execute_fn() | |
| return f"Tool '{self.name}' executed successfully" | |
| class NfcTagData: | |
| uid: str | |
| tag_type: str | |
| ndef_records: Dict[str, str] | |
| scanned_at: str | |
| def uhal_device_id(self) -> Optional[str]: | |
| return self.ndef_records.get("uhal_device_id") | |
| def is_uhal_tag(self) -> bool: | |
| return "uhal_device_id" in self.ndef_records | |
| class VehicleDiagnostic: | |
| vin: str | |
| soc_percent: float | |
| soh_percent: float | |
| cell_voltage_delta_mv: float | |
| insulation_resistance_kohm: float | |
| temperature_c: float | |
| charging_status: str | |
| error_codes: List[str] | |
| timestamp: str | |
| class BleDevice: | |
| name: str | |
| mac_address: str | |
| rssi: int | |
| connected: bool | |
| services: List[str] | |
| is_honeywell: bool = False | |
| class AuditEntry: | |
| timestamp: str | |
| event_type: str | |
| severity: str | |
| user_id: str | |
| message: str | |
| details: Dict[str, Any] = field(default_factory=dict) | |
| # ============================================================ | |
| # SERVICE LAYER (Simulated Backend) | |
| # ============================================================ | |
| class HoneywellSdkService: | |
| """Simulated Honeywell CT45P SDK bindings""" | |
| def __init__(self): | |
| self.scanner_active = False | |
| self.device_id = "HON-CT45P-XP-A11-" + hashlib.sha256(b"ct45p_root").hexdigest()[:12].upper() | |
| self.firmware_version = "4.2.1-REL" | |
| self.android_version = "11" | |
| self.ndk_loaded = True | |
| self.sdk_loaded = True | |
| def scan_barcode(self) -> Dict[str, Any]: | |
| barcodes = [ | |
| "EV-BATTERY-PACK-BYD-72KWH-2024", | |
| "OBD2-DONGLE-VCI-BT60-SERIAL-44821", | |
| "NFC-TAG-NTAG215-UID-04D2AABBCC", | |
| "CHARGE-POLE-CCS2-SESSION-78451", | |
| "MOTOR-PMSM-150KW-SN-M20241128", | |
| ] | |
| code = random.choice(barcodes) | |
| return { | |
| "barcode": code, | |
| "format": random.choice(["CODE128", "QR", "DATAMATRIX", "PDF417"]), | |
| "timestamp": datetime.datetime.now().isoformat(), | |
| "scanner": "Honeywell Mobility SDK N6700", | |
| "device": self.device_id, | |
| } | |
| def get_obd_data(self) -> Dict[str, Any]: | |
| return { | |
| "protocol": "ISO 15765-4 (CAN)", | |
| "vin": f"WBA3E5G0{random.randint(100000,999999)}", | |
| "soc": round(random.uniform(45, 98), 1), | |
| "soh": round(random.uniform(88, 99.5), 1), | |
| "cell_delta_mv": round(random.uniform(5, 35), 1), | |
| "insulation_kohm": round(random.uniform(800, 2500), 0), | |
| "temp_c": round(random.uniform(18, 42), 1), | |
| "charging": random.choice(["Idle", "AC Charging", "DC Fast Charge", "Balancing"]), | |
| "dtcs": random.choice([[], ["P0A80"], ["P0A80", "P0AFA"], ["U0100"]]), | |
| "timestamp": datetime.datetime.now().isoformat(), | |
| } | |
| def get_wifi_diagnostics(self) -> Dict[str, Any]: | |
| return { | |
| "ssid": "HON-SERVICE-NET-5G", | |
| "rssi_dbm": random.randint(-65, -30), | |
| "link_speed_mbps": random.choice([54, 72, 150, 300, 433]), | |
| "channel": random.choice([36, 40, 44, 48, 149, 153]), | |
| "security": "WPA3-Enterprise", | |
| "connected": True, | |
| "timestamp": datetime.datetime.now().isoformat(), | |
| } | |
| def sync_local_libraries(self) -> Dict[str, Any]: | |
| return { | |
| "bms_db": "synced", | |
| "firmware_repo": "synced", | |
| "diagnostic_codes": "synced", | |
| "calibration_tables": "synced", | |
| "honeywell_ndk": "loaded", | |
| "honeywell_sdk": "loaded", | |
| "agent_sdk": "loaded", | |
| "powertools": "loaded", | |
| "timestamp": datetime.datetime.now().isoformat(), | |
| } | |
| class UhalHardwareDiagnostics: | |
| """UHAL Gateway & Manager for low-level hardware access""" | |
| def __init__(self): | |
| self.permissive_mode = False | |
| self.usb_dongle_attached = False | |
| self.active_source = DataSourcePriority.NATIVE_BLE | |
| def enable_permissive_mode(self) -> Dict[str, Any]: | |
| self.permissive_mode = True | |
| return { | |
| "mode": "permissive", | |
| "status": "enabled", | |
| "hardware_root": "Honeywell CT45P XP", | |
| "kernel_access": True, | |
| "timestamp": datetime.datetime.now().isoformat(), | |
| } | |
| def get_bus_audit(self) -> Dict[str, Any]: | |
| return { | |
| "integrity_percent": round(random.uniform(98, 100), 1), | |
| "buffer_loss_percent": 0.0, | |
| "signal_quality": random.choice(["Ausgezeichnet", "Gut", "Akzeptabel"]), | |
| "usb_packets_tx": random.randint(10000, 50000), | |
| "usb_packets_rx": random.randint(10000, 50000), | |
| "usb_errors": 0, | |
| "ble_packets_tx": random.randint(5000, 20000), | |
| "ble_packets_rx": random.randint(5000, 20000), | |
| "ble_errors": 0, | |
| "timestamp": datetime.datetime.now().isoformat(), | |
| } | |
| def set_usb_dongle(self, attached: bool): | |
| self.usb_dongle_attached = attached | |
| if attached: | |
| self.active_source = DataSourcePriority.USB_HARDWARE | |
| else: | |
| self.active_source = DataSourcePriority.NATIVE_BLE | |
| class SecureBleLeManager: | |
| """BLE LE Manager with E2E encryption""" | |
| def __init__(self): | |
| self.connected_devices: List[BleDevice] = [] | |
| self.encryption_active = True | |
| self.aes_key_id = "HON-CT45P-SECURE-KEY-2026-X1" | |
| def scan_peripherals(self) -> List[Dict[str, Any]]: | |
| devices = [ | |
| {"name": "OBD2-VCI-BT60", "mac": "00:1A:7D:DA:71:13", "rssi": random.randint(-55, -25), "type": "OBD2_Dongle", "honeywell": True}, | |
| {"name": "BMS-Telemetry-Sensor", "mac": "5C:CF:7F:C2:AA:BB", "rssi": random.randint(-65, -35), "type": "BMS_Sensor", "honeywell": True}, | |
| {"name": "EV-Charger-CCS2", "mac": "AC:CF:85:3D:12:44", "rssi": random.randint(-70, -40), "type": "Charger", "honeywell": False}, | |
| {"name": "Thermal-Probe-BLE", "mac": "AA:BB:CC:DD:EE:FF", "rssi": random.randint(-60, -30), "type": "Thermal", "honeywell": True}, | |
| {"name": "Isolation-Monitor", "mac": "11:22:33:44:55:66", "rssi": random.randint(-75, -45), "type": "Isolation", "honeywell": False}, | |
| ] | |
| return devices | |
| def get_telemetry(self) -> Dict[str, Any]: | |
| return { | |
| "source": "BLE_LE_Encrypted", | |
| "encryption": "AES-256-GCM", | |
| "key_id": self.aes_key_id, | |
| "e2e_active": self.encryption_active, | |
| "voltage_pack_v": round(random.uniform(350, 405), 2), | |
| "current_a": round(random.uniform(-50, 150), 2), | |
| "power_kw": round(random.uniform(-20, 60), 2), | |
| "temp_max_c": round(random.uniform(25, 45), 1), | |
| "temp_min_c": round(random.uniform(15, 30), 1), | |
| "isolation_mohm": round(random.uniform(1.0, 5.0), 3), | |
| "timestamp": datetime.datetime.now().isoformat(), | |
| } | |
| class EmobilityAiAgent: | |
| """AI Agent with MCP architecture — synchronous to avoid asyncio issues""" | |
| def __init__(self): | |
| self.registered_tools: List[McpTool] = [] | |
| self.conversation_history: List[Dict[str, str]] = [] | |
| self._register_default_tools() | |
| def _register_default_tools(self): | |
| default_tools = [ | |
| McpTool(id="get_bms_status", name="BMS Telemetrie-Abtastung", description="Analysiert Zellspannungen und SOH des Hochvoltspeichers", category="diagnostics", icon="🔋"), | |
| McpTool(id="run_sys_audit", name="uHAL Bus-Audit", description="Prüft USB-C Transportintegrität & Paketpuffer", category="system", icon="🔍"), | |
| McpTool(id="obd_scan", name="OBD-II Diagnose", description="Führt vollständige OBD-II Fahrzeugdiagnose durch", category="diagnostics", icon="🚗"), | |
| McpTool(id="ble_telemetry", name="BLE Telemetrie-Stream", description="Liest Echtzeit-Sensordaten über verschlüsselte BLE-Verbindung", category="connectivity", icon="📡"), | |
| McpTool(id="nfc_identify", name="NFC Fahrzeug-Identifikation", description="Identifiziert Fahrzeug über NFC Smart-Card Tap", category="connectivity", icon="💳"), | |
| McpTool(id="wifi_diag", name="WiFi Netzwerk-Diagnose", description="Analysiert WiFi-Verbindungsqualität und Netzwerkparameter", category="connectivity", icon="📶"), | |
| McpTool(id="barcode_scan", name="Barcode Scanner", description="Löst Honeywell N6700 Hardware-Barcode-Scan aus", category="hardware", icon="📷"), | |
| McpTool(id="lib_sync", name="Bibliotheks-Synchronisation", description="Synchronisiert alle Honeywell-Bibliotheken und Datenbanken lokal", category="system", icon="🔄"), | |
| McpTool(id="e2e_encrypt", name="E2E Verschlüsselung-Check", description="Verifiziert End-to-End Verschlüsselung aller Telemetriekanäle", category="security", icon="🔐"), | |
| McpTool(id="factory_reset", name="Factory Reset", description="Sicherer Factory Reset mit Hardware-Token-Verifikation", category="system", icon="⚠️"), | |
| ] | |
| self.registered_tools = default_tools | |
| def register_tool(self, tool: McpTool): | |
| self.registered_tools.append(tool) | |
| def get_tools_by_category(self) -> Dict[str, List[McpTool]]: | |
| categories: Dict[str, List[McpTool]] = {} | |
| for tool in self.registered_tools: | |
| if tool.category not in categories: | |
| categories[tool.category] = [] | |
| categories[tool.category].append(tool) | |
| return categories | |
| def ask_agent(self, prompt: str, context: str = "") -> str: | |
| """Synchronous agent — avoids asyncio.run() inside Gradio's event loop""" | |
| self.conversation_history.append({"role": "user", "content": prompt}) | |
| prompt_lower = prompt.lower() | |
| if any(kw in prompt_lower for kw in ["batterie", "bms", "soc", "soh", "zellspannung"]): | |
| response = ( | |
| "🔋 **BMS Diagnose-Ergebnis:**\n\n" | |
| "- **State of Health (SOH):** 96.8% — Nominal\n" | |
| "- **State of Charge (SOC):** 72.4% — Normal\n" | |
| "- **Zellspannungs-Delta (ΔV):** 12 mV — Innerhalb Toleranz (<30mV)\n" | |
| "- **Isolationswiderstand:** 1.400 kΩ — Sicher (>1 kΩ)\n" | |
| "- **Temperatur-Spread:** 4.2°C — Normal\n\n" | |
| "✅ Keine Anomalie erkannt. Hochvoltspeicher ist in gutem Zustand.\n" | |
| "📋 Empfehlung: Nächste Kalibrierung in 6 Monaten." | |
| ) | |
| elif any(kw in prompt_lower for kw in ["obd", "fehlercode", "dtc", "diagnose"]): | |
| response = ( | |
| "🚗 **OBD-II Diagnose-Ergebnis:**\n\n" | |
| "- **Protokoll:** ISO 15765-4 (CAN 500k)\n" | |
| "- **Fehlercodes (DTCs):** Keine aktiven DTCs\n" | |
| "- **Readiness Monitors:** Alle bestanden\n" | |
| "- **Emission-Status:** Bereit\n\n" | |
| "✅ Fahrzeug-ECU meldet keinen Fehler." | |
| ) | |
| elif any(kw in prompt_lower for kw in ["verschlüsselung", "encryption", "sicherheit", "security"]): | |
| response = ( | |
| "🔐 **Sicherheits-Audit:**\n\n" | |
| "- **E2E Verschlüsselung:** AES-256-GCM aktiv\n" | |
| "- **Hardware-Root-of-Trust:** Honeywell CT45P verifiziert\n" | |
| "- **BLE-Encryption:** Verschlüsselte GATT-Charakteristiken\n" | |
| "- **USB-C:** TLS 1.3 auf serieller Verbindung\n" | |
| "- **Token-Status:** SIL-2 validiert\n\n" | |
| "✅ Alle Kommunikationskanäle sind verschlüsselt." | |
| ) | |
| elif any(kw in prompt_lower for kw in ["reset", "werkszustand", "factory"]): | |
| response = ( | |
| "⚠️ **Factory Reset Anforderung:**\n\n" | |
| "Für Factory Reset wird **SIL-Level 3+** benötigt.\n" | |
| "1. Hardware-Token verifizieren\n" | |
| "2. Backup erstellen\n" | |
| "3. Reset ausführen\n" | |
| "4. Post-Reset-Verifikation\n\n" | |
| "📋 Verwende den Factory Reset Tab im System-Panel." | |
| ) | |
| else: | |
| response = ( | |
| f"🤖 **KI-Antwort:**\n\n" | |
| f"Anfrage analysiert: '{prompt[:60]}...'\n\n" | |
| f"Verfügbare MCP-Tools: {len(self.registered_tools)}\n" | |
| f"Aktive Verbindungen: BLE + USB-C Hybrid\n" | |
| f"Hardware: Honeywell CT45P XP (Android 11)\n\n" | |
| "💡 Tipp: Fragen zu Batterie/BMS, OBD-Diagnose, Verschlüsselung oder Factory Reset werden kontextbezogen beantwortet." | |
| ) | |
| self.conversation_history.append({"role": "assistant", "content": response}) | |
| return response | |
| class AuditLogger: | |
| """Central audit logging system""" | |
| def __init__(self): | |
| self.entries: List[AuditEntry] = [] | |
| def log(self, event_type: str, severity: str, user_id: str, message: str, details: Dict = None): | |
| entry = AuditEntry( | |
| timestamp=datetime.datetime.now().isoformat(), | |
| event_type=event_type, | |
| severity=severity, | |
| user_id=user_id, | |
| message=message, | |
| details=details or {}, | |
| ) | |
| self.entries.append(entry) | |
| if len(self.entries) > 500: | |
| self.entries = self.entries[-500:] | |
| def get_recent(self, count: int = 50) -> List[Dict]: | |
| return [asdict(e) for e in self.entries[-count:]] | |
| class HardwareTokenManager: | |
| """Hardware Root-of-Trust Token Manager""" | |
| def __init__(self): | |
| self.hardware_root_id = "HWR-" + hashlib.sha256(b"honeywell_ct45p_root").hexdigest()[:16].upper() | |
| self.device_root_id = "DEV-" + hashlib.sha256(b"ct45p_device").hexdigest()[:16].upper() | |
| self.verified_tokens: Dict[str, HardwareToken] = {} | |
| def create_token(self, permissions: List[str], sil_level: int = 1) -> HardwareToken: | |
| now = datetime.datetime.now() | |
| token = HardwareToken( | |
| token_id="TKN-" + hashlib.sha256(str(now.timestamp()).encode()).hexdigest()[:12].upper(), | |
| hardware_id=self.hardware_root_id, | |
| device_id=self.device_root_id, | |
| issued_at=now.isoformat(), | |
| expires_at=(now + datetime.timedelta(hours=8)).isoformat(), | |
| permissions=permissions, | |
| sil_level=sil_level, | |
| ) | |
| self.verified_tokens[token.token_id] = token | |
| return token | |
| def verify_token(self, token: HardwareToken) -> bool: | |
| if not token.is_valid(): | |
| return False | |
| if token.hardware_id != self.hardware_root_id: | |
| return False | |
| if token.device_id != self.device_root_id: | |
| return False | |
| return True | |
| # ============================================================ | |
| # GLOBAL SERVICE INSTANCES | |
| # ============================================================ | |
| honeywell_sdk = HoneywellSdkService() | |
| uhal_diag = UhalHardwareDiagnostics() | |
| ble_manager = SecureBleLeManager() | |
| ai_agent = EmobilityAiAgent() | |
| audit_logger = AuditLogger() | |
| token_manager = HardwareTokenManager() | |
| # Enable UHAL permissive mode on startup | |
| uhal_diag.enable_permissive_mode() | |
| audit_logger.log("system", "info", "system", "UHAL Permissive Mode aktiviert") | |
| audit_logger.log("system", "info", "system", "Honeywell NDK/SDK/AgentSDK/PowerTools geladen") | |
| # ============================================================ | |
| # HANDLER FUNCTIONS | |
| # ============================================================ | |
| def handle_barcode_scan(): | |
| result = honeywell_sdk.scan_barcode() | |
| audit_logger.log("hardware", "info", "scanner", f"Barcode gescannt: {result['barcode']}", result) | |
| return json.dumps(result, indent=2, ensure_ascii=False) | |
| def handle_obd_diagnosis(): | |
| result = honeywell_sdk.get_obd_data() | |
| audit_logger.log("diagnostics", "info", "obd_service", "OBD-II Diagnose durchgeführt", result) | |
| return json.dumps(result, indent=2, ensure_ascii=False) | |
| def handle_wifi_diag(): | |
| result = honeywell_sdk.get_wifi_diagnostics() | |
| return json.dumps(result, indent=2, ensure_ascii=False) | |
| def handle_lib_sync(): | |
| result = honeywell_sdk.sync_local_libraries() | |
| audit_logger.log("system", "info", "agent_sdk", "Bibliotheken synchronisiert", result) | |
| return json.dumps(result, indent=2, ensure_ascii=False) | |
| def handle_uhal_audit(): | |
| result = uhal_diag.get_bus_audit() | |
| audit_logger.log("system", "info", "uhal_manager", "Bus-Audit durchgeführt", result) | |
| return json.dumps(result, indent=2, ensure_ascii=False) | |
| def handle_ble_scan(): | |
| devices = ble_manager.scan_peripherals() | |
| audit_logger.log("connectivity", "info", "ble_le", f"BLE Scan: {len(devices)} Geräte gefunden") | |
| return json.dumps(devices, indent=2, ensure_ascii=False) | |
| def handle_ble_telemetry(): | |
| result = ble_manager.get_telemetry() | |
| return json.dumps(result, indent=2, ensure_ascii=False) | |
| def handle_usb_toggle(attached): | |
| uhal_diag.set_usb_dongle(attached) | |
| source = "USB-C Hardware" if attached else "BLE LE" | |
| audit_logger.log("connectivity", "info", "hybrid_mgr", f"Datenquelle gewechselt: {source}") | |
| return f"✅ Aktive Datenquelle: **{source}**\nUSB-Dongle: {'Angesteckt' if attached else 'Entfernt'}" | |
| def handle_nfc_scan(): | |
| tag = NfcTagData( | |
| uid="04:D2:AA:BB:CC:55:01", | |
| tag_type=NfcTagType.NTAG215.value, | |
| ndef_records={ | |
| "uhal_device_id": "HON-STEUERGERAET-BT60", | |
| "uhal_action": "IDENTIFY", | |
| "vehicle_vin": "WBA3E5G0C234567", | |
| "work_order": "WO-2024-00847", | |
| }, | |
| scanned_at=datetime.datetime.now().isoformat(), | |
| ) | |
| result = asdict(tag) | |
| audit_logger.log("connectivity", "info", "nfc_sensor", f"NFC Tag gelesen: {tag.uhal_device_id}", result) | |
| return json.dumps(result, indent=2, ensure_ascii=False) | |
| def handle_mcp_execute(tool_id: str): | |
| tools_map = {t.id: t for t in ai_agent.registered_tools} | |
| if tool_id not in tools_map: | |
| return f"❌ Tool '{tool_id}' nicht gefunden" | |
| tool = tools_map[tool_id] | |
| if tool_id == "get_bms_status": | |
| result = f"SoH: 96.8%, ΔV: 12mV, Isolationswiderstand: 1400kΩ. Nominal." | |
| elif tool_id == "run_sys_audit": | |
| audit = uhal_diag.get_bus_audit() | |
| result = f"Integrität: {audit['integrity_percent']}%, Pufferverlust: {audit['buffer_loss_percent']}%, Signal: {audit['signal_quality']}" | |
| elif tool_id == "obd_scan": | |
| obd = honeywell_sdk.get_obd_data() | |
| result = f"VIN: {obd['vin']}, SOC: {obd['soc']}%, SOH: {obd['soh']}%, DTCs: {obd['dtcs']}" | |
| elif tool_id == "ble_telemetry": | |
| tel = ble_manager.get_telemetry() | |
| result = f"Pack: {tel['voltage_pack_v']}V, {tel['current_a']}A, E2E: {tel['encryption']}" | |
| elif tool_id == "nfc_identify": | |
| result = "UID: 04:D2:AA:BB:CC:55:01, Device: HON-STEUERGERAET-BT60" | |
| elif tool_id == "wifi_diag": | |
| wifi = honeywell_sdk.get_wifi_diagnostics() | |
| result = f"SSID: {wifi['ssid']}, RSSI: {wifi['rssi_dbm']}dBm, Speed: {wifi['link_speed_mbps']}Mbps" | |
| elif tool_id == "barcode_scan": | |
| bc = honeywell_sdk.scan_barcode() | |
| result = f"Code: {bc['barcode']}, Format: {bc['format']}" | |
| elif tool_id == "lib_sync": | |
| result = "Alle Honeywell-Bibliotheken und Datenbanken synchronisiert und lokal gesichert." | |
| elif tool_id == "e2e_encrypt": | |
| result = "AES-256-GCM auf allen Kanälen aktiv. Hardware-Root-of-Trust verifiziert." | |
| elif tool_id == "factory_reset": | |
| result = "⚠️ Factory Reset erfordert SIL-Level 3+ Hardware-Token. Bitte System-Panel verwenden." | |
| else: | |
| result = f"Tool '{tool.name}' ausgeführt." | |
| audit_logger.log("mcp", "info", "mcp_pipeline", f"MCP Tool ausgeführt: {tool.name}", {"tool_id": tool_id, "result": result}) | |
| return f"{tool.icon} **{tool.name}**\n\n{result}" | |
| def handle_ai_chat(message, history): | |
| """ChatInterface handler — synchronous to avoid event loop conflicts""" | |
| response = ai_agent.ask_agent(message) | |
| audit_logger.log("ai_agent", "info", "tinyagent", f"KI-Anfrage: {message[:50]}...") | |
| return response | |
| def handle_create_token(permissions, sil_level): | |
| perms = [p.strip() for p in permissions.split(",") if p.strip()] | |
| token = token_manager.create_token(perms, int(sil_level)) | |
| audit_logger.log("security", "info", "token_mgr", f"Token erstellt: {token.token_id}", asdict(token)) | |
| return json.dumps(asdict(token), indent=2, ensure_ascii=False) | |
| def handle_verify_token(token_json): | |
| try: | |
| data = json.loads(token_json) | |
| token = HardwareToken(**data) | |
| is_valid = token_manager.verify_token(token) | |
| if is_valid: | |
| return f"✅ Token **VERIFIZIERT**\n- Token-ID: {token.token_id}\n- SIL-Level: {token.sil_level}\n- Berechtigungen: {', '.join(token.permissions)}\n- Gültig bis: {token.expires_at}" | |
| else: | |
| return "❌ Token **UNGÜLTIG** — Hardware-ID Mismatch oder abgelaufen" | |
| except Exception as e: | |
| return f"❌ Fehler bei Token-Verifikation: {str(e)}" | |
| def handle_factory_reset(level, reason, backup): | |
| level_map = { | |
| "Soft (App-Daten)": ResetLevel.SOFT, | |
| "Standard (App+Cache)": ResetLevel.STANDARD, | |
| "Hard (Alles außer MDM)": ResetLevel.HARD, | |
| "Factory (Vollständig)": ResetLevel.FACTORY, | |
| } | |
| reset_lvl = level_map.get(level, ResetLevel.SOFT) | |
| required_sil = 3 if reset_lvl in [ResetLevel.HARD, ResetLevel.FACTORY] else 1 | |
| token = token_manager.create_token( | |
| permissions=[f"level_{i}" for i in range(1, required_sil + 1)], | |
| sil_level=required_sil, | |
| ) | |
| result = f"""⚠️ **Factory Reset Protokoll** | |
| **Reset-Level:** {reset_lvl.value.upper()} | |
| **Erforderliches SIL-Level:** {required_sil} | |
| **Hardware-Token:** {token.token_id} | |
| **Backup:** {'Ja' if backup else 'Nein'} | |
| **Grund:** {reason} | |
| **Ausführungsschritte:** | |
| 1. ✅ Token verifiziert (SIL-{required_sil}) | |
| 2. {"✅ Backup erstellt" if backup else "⏭️ Backup übersprungen"} | |
| 3. ✅ Reset ausgeführt: {reset_lvl.value} | |
| 4. ✅ Post-Reset-Verifikation bestanden | |
| **Dauer:** 2.3 Sekunden | |
| **Status:** ERFOLGREICH""" | |
| audit_logger.log("system", "critical", "factory_reset", f"Factory Reset: {reset_lvl.value}", {"level": reset_lvl.value, "reason": reason}) | |
| return result | |
| def handle_get_audit_log(): | |
| entries = audit_logger.get_recent(30) | |
| if not entries: | |
| return "Keine Audit-Einträge vorhanden." | |
| lines = [] | |
| for e in entries: | |
| icon = {"info": "ℹ️", "warning": "⚠️", "critical": "🔴", "error": "❌"}.get(e["severity"], "•") | |
| lines.append(f"{icon} `{e['timestamp'][:19]}` [{e['severity'].upper()}] {e['event_type']} — {e['message']}") | |
| return "\n".join(lines) | |
| def handle_get_system_status(): | |
| return json.dumps({ | |
| "device": honeywell_sdk.device_id, | |
| "firmware": honeywell_sdk.firmware_version, | |
| "android": honeywell_sdk.android_version, | |
| "ndk_loaded": honeywell_sdk.ndk_loaded, | |
| "sdk_loaded": honeywell_sdk.sdk_loaded, | |
| "uhal_mode": "permissive" if uhal_diag.permissive_mode else "restricted", | |
| "usb_dongle": uhal_diag.usb_dongle_attached, | |
| "active_source": uhal_diag.active_source.value, | |
| "ble_encryption": ble_manager.encryption_active, | |
| "mcp_tools": len(ai_agent.registered_tools), | |
| "audit_entries": len(audit_logger.entries), | |
| "hardware_root_id": token_manager.hardware_root_id, | |
| "device_root_id": token_manager.device_root_id, | |
| }, indent=2, ensure_ascii=False) | |
| def handle_add_mcp_tool(tool_id, tool_name, tool_desc, tool_category): | |
| if not tool_id or not tool_name: | |
| return "❌ Tool-ID und Name sind erforderlich.", gr.Dropdown(choices=[t.id for t in ai_agent.registered_tools]) | |
| existing_ids = [t.id for t in ai_agent.registered_tools] | |
| if tool_id in existing_ids: | |
| return f"❌ Tool-ID '{tool_id}' existiert bereits.", gr.Dropdown(choices=existing_ids) | |
| new_tool = McpTool(id=tool_id, name=tool_name, description=tool_desc, category=tool_category, icon="⚡") | |
| ai_agent.register_tool(new_tool) | |
| audit_logger.log("mcp", "info", "mcp_registry", f"Neues MCP-Tool registriert: {tool_name}") | |
| updated_ids = [t.id for t in ai_agent.registered_tools] | |
| return f"✅ Tool '{tool_name}' ({tool_id}) in Kategorie '{tool_category}' registriert.", gr.Dropdown(choices=updated_ids) | |
| def handle_refresh_status(): | |
| return json.loads(handle_get_system_status()) | |
| # ============================================================ | |
| # GRADIO 6 APPLICATION | |
| # ============================================================ | |
| custom_theme = gr.themes.Soft( | |
| primary_hue="red", | |
| secondary_hue="orange", | |
| neutral_hue="slate", | |
| font=gr.themes.GoogleFont("Inter"), | |
| text_size="md", | |
| spacing_size="md", | |
| radius_size="md", | |
| ).set( | |
| button_primary_background_fill="*primary_600", | |
| button_primary_background_fill_hover="*primary_700", | |
| block_title_text_weight="600", | |
| ) | |
| with gr.Blocks() as demo: | |
| gr.Markdown( | |
| """ | |
| # 🔧 Honeywell CT45P XP — E-Mobility Service Werkstatt | |
| ### UHAL Edge Workspace | Android 11 | NDK/SDK/AgentSDK/PowerTools | |
| [Built with anycoder](https://huggingface.co/spaces/akhaliq/anycoder) | |
| """ | |
| ) | |
| # System status bar | |
| with gr.Row(): | |
| status_box = gr.JSON(label="System Status", value=json.loads(handle_get_system_status()), height=120) | |
| refresh_status_btn = gr.Button("🔄 Status aktualisieren", size="sm") | |
| refresh_status_btn.click(handle_refresh_status, outputs=status_box) | |
| with gr.Tabs(): | |
| # ============================================================ | |
| # TAB 1: HARDWARE DIAGNOSTICS | |
| # ============================================================ | |
| with gr.Tab("🔍 Hardware Diagnose"): | |
| gr.Markdown("### Honeywell Mobility SDK & PowerTools — Echtzeit-Diagnose") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 📷 Barcode Scanner (N6700)") | |
| scan_btn = gr.Button("Hardware-Scan auslösen", variant="primary") | |
| scan_result = gr.Code(language="json", label="Scan-Ergebnis", lines=8) | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 🚗 OBD-II Diagnose (PowerTools)") | |
| obd_btn = gr.Button("OBD-II Diagnose starten", variant="primary") | |
| obd_result = gr.Code(language="json", label="OBD-Ergebnis", lines=8) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 📶 WiFi Diagnose") | |
| wifi_btn = gr.Button("WiFi-Status prüfen", variant="secondary") | |
| wifi_result = gr.Code(language="json", label="WiFi-Ergebnis", lines=6) | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 🔄 Bibliotheks-Sync") | |
| sync_btn = gr.Button("Honeywell Libs synchronisieren", variant="secondary") | |
| sync_result = gr.Code(language="json", label="Sync-Ergebnis", lines=6) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 💳 NFC Smart Card") | |
| nfc_btn = gr.Button("NFC Tap-to-Identify", variant="primary") | |
| nfc_result = gr.Code(language="json", label="NFC-Ergebnis", lines=10) | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 🔍 uHAL Bus-Audit") | |
| audit_btn = gr.Button("Bus-Integrität prüfen", variant="secondary") | |
| audit_result = gr.Code(language="json", label="Audit-Ergebnis", lines=10) | |
| scan_btn.click(handle_barcode_scan, outputs=scan_result) | |
| obd_btn.click(handle_obd_diagnosis, outputs=obd_result) | |
| wifi_btn.click(handle_wifi_diag, outputs=wifi_result) | |
| sync_btn.click(handle_lib_sync, outputs=sync_result) | |
| nfc_btn.click(handle_nfc_scan, outputs=nfc_result) | |
| audit_btn.click(handle_uhal_audit, outputs=audit_result) | |
| # ============================================================ | |
| # TAB 2: BLE & CONNECTIVITY | |
| # ============================================================ | |
| with gr.Tab("📡 BLE LE & Konnektivität"): | |
| gr.Markdown("### BLE 6.0 LE — E2E Verschlüsselte Telemetrie & USB-C Hybrid") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 🔵 BLE Peripheral Scan") | |
| ble_scan_btn = gr.Button("BLE LE Scan starten", variant="primary") | |
| ble_scan_result = gr.Code(language="json", label="BLE Geräte", lines=15) | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 📡 Echtzeit-Telemetrie (Verschlüsselt)") | |
| ble_tel_btn = gr.Button("Telemetrie abrufen (AES-256-GCM)", variant="primary") | |
| ble_tel_result = gr.Code(language="json", label="Telemetrie-Daten", lines=12) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 🔌 USB-C Hybrid Hot-Swap") | |
| usb_toggle = gr.Checkbox(label="USB-C OBD2-Dongle angesteckt", value=False) | |
| usb_status = gr.Textbox(label="Datenquelle", lines=3, value="Aktive Datenquelle: **BLE LE**\nUSB-Dongle: Entfernt") | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 🔐 E2E Verschlüsselung") | |
| gr.JSON( | |
| value={ | |
| "algorithm": "AES-256-GCM", | |
| "key_derivation": "HKDF-SHA256", | |
| "key_id": ble_manager.aes_key_id, | |
| "channels": ["BLE_GATT", "USB_C_SERIAL", "NFC_NDEF"], | |
| "status": "active", | |
| "hardware_root": token_manager.hardware_root_id, | |
| }, | |
| label="Verschlüsselungs-Status", | |
| ) | |
| ble_scan_btn.click(handle_ble_scan, outputs=ble_scan_result) | |
| ble_tel_btn.click(handle_ble_telemetry, outputs=ble_tel_result) | |
| usb_toggle.change(handle_usb_toggle, inputs=usb_toggle, outputs=usb_status) | |
| # ============================================================ | |
| # TAB 3: MCP PIPELINE | |
| # ============================================================ | |
| with gr.Tab("🔧 MCP Pipeline"): | |
| gr.Markdown("### MCP Tool-Registry & Drag-Integration — Diagnose-Pipeline Konstruktor") | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| gr.Markdown("#### 📋 Verfügbare MCP-Tools") | |
| mcp_tool_select = gr.Dropdown( | |
| choices=[t.id for t in ai_agent.registered_tools], | |
| label="Tool auswählen", | |
| info="Wähle ein MCP-Tool zur Ausführung", | |
| ) | |
| mcp_execute_btn = gr.Button("Tool ausführen", variant="primary") | |
| mcp_result = gr.Textbox(label="Ausführungsergebnis", lines=6, max_lines=15) | |
| with gr.Column(scale=3): | |
| gr.Markdown("#### 🗂️ Tool-Kategorien") | |
| categories = ai_agent.get_tools_by_category() | |
| cat_data = [] | |
| for cat, tools in categories.items(): | |
| for t in tools: | |
| cat_data.append([t.icon, t.id, t.name, t.description, cat]) | |
| gr.Dataframe( | |
| value=cat_data, | |
| headers=["", "ID", "Name", "Beschreibung", "Kategorie"], | |
| label="MCP Tool-Registry", | |
| interactive=False, | |
| column_widths=[40, 150, 200, 300, 120], | |
| height=350, | |
| ) | |
| gr.Markdown("#### ➕ Eigenes MCP-Tool registrieren") | |
| with gr.Row(): | |
| new_tool_id = gr.Textbox(label="Tool-ID", placeholder="z.B. custom_ev_check") | |
| new_tool_name = gr.Textbox(label="Name", placeholder="z.B. EV Fahrzeug-Check") | |
| new_tool_desc = gr.Textbox(label="Beschreibung", placeholder="z.B. Prüft Fahrzeug-Status") | |
| new_tool_cat = gr.Dropdown( | |
| choices=["diagnostics", "connectivity", "system", "security", "hardware", "custom"], | |
| label="Kategorie", | |
| value="custom", | |
| ) | |
| add_tool_btn = gr.Button("Tool registrieren", variant="secondary") | |
| add_tool_result = gr.Textbox(label="Registrierungs-Status", lines=2) | |
| mcp_execute_btn.click(handle_mcp_execute, inputs=mcp_tool_select, outputs=mcp_result) | |
| add_tool_btn.click( | |
| handle_add_mcp_tool, | |
| inputs=[new_tool_id, new_tool_name, new_tool_desc, new_tool_cat], | |
| outputs=[add_tool_result, mcp_tool_select], | |
| ) | |
| # ============================================================ | |
| # TAB 4: AI AGENT | |
| # ============================================================ | |
| with gr.Tab("🤖 KI Agent (TinyAgent)"): | |
| gr.Markdown("### HuggingFace TinyAgent — Kontextbezogene E-Mobility Diagnose-KI") | |
| with gr.Row(): | |
| with gr.Column(scale=3): | |
| ai_chat = gr.ChatInterface( | |
| fn=handle_ai_chat, | |
| title="E-Mobility KI-Assistent", | |
| description="Fragen zu Batterie/BMS, OBD-Diagnose, Verschlüsselung, Factory Reset und mehr.", | |
| examples=[ | |
| "Batterie-Anomalieprüfung anfordern", | |
| "OBD-II Fehlercodes auslesen", | |
| "E2E Verschlüsselung verifizieren", | |
| "Factory Reset durchführen", | |
| "BMS Zellspannungs-Analyse", | |
| "Isolationswiderstand prüfen", | |
| ], | |
| ) | |
| with gr.Column(scale=2): | |
| gr.Markdown("#### 🧠 Agent-Kontext") | |
| gr.JSON( | |
| value={ | |
| "model": "meta-llama/Llama-2-7b-chat-hf (Edge)", | |
| "architecture": "MCP (Model Context Protocol)", | |
| "tools_available": len(ai_agent.registered_tools), | |
| "context_injection": "BMS/OBD Telemetrie", | |
| "hardware_binding": "Honeywell CT45P XP", | |
| "encryption": "E2E AES-256-GCM", | |
| "offline_capable": True, | |
| "huggingface_integration": True, | |
| }, | |
| label="Agent-Konfiguration", | |
| ) | |
| gr.Markdown("#### 📊 Verfügbare MCP-Kontexte") | |
| context_tools = [] | |
| for t in ai_agent.registered_tools: | |
| context_tools.append([t.icon, t.name, t.category]) | |
| gr.Dataframe( | |
| value=context_tools, | |
| headers=["", "Tool", "Kategorie"], | |
| label="KI-Kontext-Quellen", | |
| interactive=False, | |
| height=300, | |
| ) | |
| # ============================================================ | |
| # TAB 5: SECURITY & TOKENS | |
| # ============================================================ | |
| with gr.Tab("🔐 Sicherheit & Tokens"): | |
| gr.Markdown("### Hardware-Root-of-Trust & SIL-Level Authentifizierung") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### 🏛️ Hardware-Root-of-Trust") | |
| gr.JSON( | |
| value={ | |
| "hardware_root_id": token_manager.hardware_root_id, | |
| "device_root_id": token_manager.device_root_id, | |
| "device": honeywell_sdk.device_id, | |
| "firmware": honeywell_sdk.firmware_version, | |
| "android": honeywell_sdk.android_version, | |
| "uhal_mode": "permissive", | |
| }, | |
| label="Root-of-Trust Identität", | |
| ) | |
| with gr.Column(scale=1): | |
| gr.Markdown("#### ➕ Token erstellen") | |
| perm_input = gr.Textbox( | |
| label="Berechtigungen (komma-getrennt)", | |
| value="level_1, level_2", | |
| placeholder="level_1, level_2, level_3, level_4", | |
| ) | |
| sil_input = gr.Slider( | |
| minimum=1, maximum=4, value=1, step=1, | |
| label="SIL-Level", | |
| info="1=Diagnose, 2=Konfiguration, 3=Firmware, |