joz88 commited on
Commit
ed48ec9
·
verified ·
1 Parent(s): df66f43

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +933 -0
  2. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,933 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import json
3
+ import time
4
+ import random
5
+ import hashlib
6
+ import datetime
7
+ import asyncio
8
+ from dataclasses import dataclass, field, asdict
9
+ from typing import Optional, List, Dict, Any, Callable
10
+ from enum import Enum
11
+
12
+ # ============================================================
13
+ # ENUMS & DATA MODELS
14
+ # ============================================================
15
+
16
+ class ConnectionType(Enum):
17
+ UART = "uart"
18
+ USB = "usb"
19
+ BLE = "ble"
20
+ WIFI = "wifi"
21
+ CAN = "can"
22
+ NFC = "nfc"
23
+
24
+ class ConnectionState(Enum):
25
+ DISCONNECTED = "disconnected"
26
+ CONNECTING = "connecting"
27
+ CONNECTED = "connected"
28
+ AUTHENTICATING = "authenticating"
29
+ AUTHENTICATED = "authenticated"
30
+ ERROR = "error"
31
+
32
+ class SafetyIntegrityLevel(Enum):
33
+ NONE = 0
34
+ SIL1 = 1
35
+ SIL2 = 2
36
+ SIL3 = 3
37
+ SIL4 = 4
38
+
39
+ class ResetLevel(Enum):
40
+ SOFT = "soft"
41
+ STANDARD = "standard"
42
+ HARD = "hard"
43
+ FACTORY = "factory"
44
+
45
+ class NfcTagType(Enum):
46
+ MIFARE_CLASSIC = "MifareClassic"
47
+ MIFARE_DESFIRE = "MifareDESFire"
48
+ NTAG215 = "NTAG215"
49
+ NTAG216 = "NTAG216"
50
+
51
+ class DataSourcePriority(Enum):
52
+ USB_HARDWARE = "usb_hardware"
53
+ NATIVE_BLE = "native_ble"
54
+
55
+ @dataclass
56
+ class HardwareToken:
57
+ token_id: str
58
+ hardware_id: str
59
+ device_id: str
60
+ issued_at: str
61
+ expires_at: str
62
+ permissions: List[str]
63
+ sil_level: int = 1
64
+
65
+ def is_valid(self) -> bool:
66
+ try:
67
+ return datetime.datetime.fromisoformat(self.expires_at) > datetime.datetime.now()
68
+ except:
69
+ return False
70
+
71
+ def has_permission(self, perm: str) -> bool:
72
+ return perm in self.permissions
73
+
74
+ @dataclass
75
+ class McpTool:
76
+ id: str
77
+ name: str
78
+ description: str
79
+ category: str
80
+ icon: str = "🔧"
81
+ execute_fn: Optional[Callable] = None
82
+
83
+ async def execute(self) -> str:
84
+ if self.execute_fn:
85
+ return await self.execute_fn()
86
+ return f"Tool '{self.name}' executed successfully"
87
+
88
+ @dataclass
89
+ class NfcTagData:
90
+ uid: str
91
+ tag_type: str
92
+ ndef_records: Dict[str, str]
93
+ scanned_at: str
94
+
95
+ @property
96
+ def uhal_device_id(self) -> Optional[str]:
97
+ return self.ndef_records.get("uhal_device_id")
98
+
99
+ @property
100
+ def is_uhal_tag(self) -> bool:
101
+ return "uhal_device_id" in self.ndef_records
102
+
103
+ @dataclass
104
+ class VehicleDiagnostic:
105
+ vin: str
106
+ soc_percent: float
107
+ soh_percent: float
108
+ cell_voltage_delta_mv: float
109
+ insulation_resistance_kohm: float
110
+ temperature_c: float
111
+ charging_status: str
112
+ error_codes: List[str]
113
+ timestamp: str
114
+
115
+ @dataclass
116
+ class BleDevice:
117
+ name: str
118
+ mac_address: str
119
+ rssi: int
120
+ connected: bool
121
+ services: List[str]
122
+ is_honeywell: bool = False
123
+
124
+ @dataclass
125
+ class AuditEntry:
126
+ timestamp: str
127
+ event_type: str
128
+ severity: str
129
+ user_id: str
130
+ message: str
131
+ details: Dict[str, Any] = field(default_factory=dict)
132
+
133
+
134
+ # ============================================================
135
+ # SERVICE LAYER (Simulated Backend)
136
+ # ============================================================
137
+
138
+ class HoneywellSdkService:
139
+ """Simulated Honeywell CT45P SDK bindings"""
140
+
141
+ def __init__(self):
142
+ self.scanner_active = False
143
+ self.device_id = "HON-CT45P-XP-A11-" + hashlib.sha256(b"ct45p_root").hexdigest()[:12].upper()
144
+ self.firmware_version = "4.2.1-REL"
145
+ self.android_version = "11"
146
+ self.ndk_loaded = True
147
+ self.sdk_loaded = True
148
+
149
+ def scan_barcode(self) -> Dict[str, Any]:
150
+ barcodes = [
151
+ "EV-BATTERY-PACK-BYD-72KWH-2024",
152
+ "OBD2-DONGLE-VCI-BT60-SERIAL-44821",
153
+ "NFC-TAG-NTAG215-UID-04D2AABBCC",
154
+ "CHARGE-POLE-CCS2-SESSION-78451",
155
+ "MOTOR-PMSM-150KW-SN-M20241128",
156
+ ]
157
+ code = random.choice(barcodes)
158
+ return {
159
+ "barcode": code,
160
+ "format": random.choice(["CODE128", "QR", "DATAMATRIX", "PDF417"]),
161
+ "timestamp": datetime.datetime.now().isoformat(),
162
+ "scanner": "Honeywell Mobility SDK N6700",
163
+ "device": self.device_id,
164
+ }
165
+
166
+ def get_obd_data(self) -> Dict[str, Any]:
167
+ return {
168
+ "protocol": "ISO 15765-4 (CAN)",
169
+ "vin": f"WBA3E5G0{random.randint(100000,999999)}",
170
+ "soc": round(random.uniform(45, 98), 1),
171
+ "soh": round(random.uniform(88, 99.5), 1),
172
+ "cell_delta_mv": round(random.uniform(5, 35), 1),
173
+ "insulation_kohm": round(random.uniform(800, 2500), 0),
174
+ "temp_c": round(random.uniform(18, 42), 1),
175
+ "charging": random.choice(["Idle", "AC Charging", "DC Fast Charge", "Balancing"]),
176
+ "dtcs": random.choice([[], ["P0A80"], ["P0A80", "P0AFA"], ["U0100"]]),
177
+ "timestamp": datetime.datetime.now().isoformat(),
178
+ }
179
+
180
+ def get_wifi_diagnostics(self) -> Dict[str, Any]:
181
+ return {
182
+ "ssid": "HON-SERVICE-NET-5G",
183
+ "rssi_dbm": random.randint(-65, -30),
184
+ "link_speed_mbps": random.choice([54, 72, 150, 300, 433]),
185
+ "channel": random.choice([36, 40, 44, 48, 149, 153]),
186
+ "security": "WPA3-Enterprise",
187
+ "connected": True,
188
+ "timestamp": datetime.datetime.now().isoformat(),
189
+ }
190
+
191
+ def sync_local_libraries(self) -> Dict[str, Any]:
192
+ return {
193
+ "bms_db": "synced",
194
+ "firmware_repo": "synced",
195
+ "diagnostic_codes": "synced",
196
+ "calibration_tables": "synced",
197
+ "honeywell_ndk": "loaded",
198
+ "honeywell_sdk": "loaded",
199
+ "agent_sdk": "loaded",
200
+ "powertools": "loaded",
201
+ "timestamp": datetime.datetime.now().isoformat(),
202
+ }
203
+
204
+
205
+ class UhalHardwareDiagnostics:
206
+ """UHAL Gateway & Manager for low-level hardware access"""
207
+
208
+ def __init__(self):
209
+ self.permissive_mode = False
210
+ self.usb_dongle_attached = False
211
+ self.active_source = DataSourcePriority.NATIVE_BLE
212
+
213
+ def enable_permissive_mode(self) -> Dict[str, Any]:
214
+ self.permissive_mode = True
215
+ return {
216
+ "mode": "permissive",
217
+ "status": "enabled",
218
+ "hardware_root": "Honeywell CT45P XP",
219
+ "kernel_access": True,
220
+ "timestamp": datetime.datetime.now().isoformat(),
221
+ }
222
+
223
+ def get_bus_audit(self) -> Dict[str, Any]:
224
+ return {
225
+ "integrity_percent": round(random.uniform(98, 100), 1),
226
+ "buffer_loss_percent": 0.0,
227
+ "signal_quality": random.choice(["Ausgezeichnet", "Gut", "Akzeptabel"]),
228
+ "usb_packets_tx": random.randint(10000, 50000),
229
+ "usb_packets_rx": random.randint(10000, 50000),
230
+ "usb_errors": 0,
231
+ "ble_packets_tx": random.randint(5000, 20000),
232
+ "ble_packets_rx": random.randint(5000, 20000),
233
+ "ble_errors": 0,
234
+ "timestamp": datetime.datetime.now().isoformat(),
235
+ }
236
+
237
+ def set_usb_dongle(self, attached: bool):
238
+ self.usb_dongle_attached = attached
239
+ if attached:
240
+ self.active_source = DataSourcePriority.USB_HARDWARE
241
+ else:
242
+ self.active_source = DataSourcePriority.NATIVE_BLE
243
+
244
+
245
+ class SecureBleLeManager:
246
+ """BLE LE Manager with E2E encryption"""
247
+
248
+ def __init__(self):
249
+ self.connected_devices: List[BleDevice] = []
250
+ self.encryption_active = True
251
+ self.aes_key_id = "HON-CT45P-SECURE-KEY-2026-X1"
252
+
253
+ def scan_peripherals(self) -> List[Dict[str, Any]]:
254
+ devices = [
255
+ {"name": "OBD2-VCI-BT60", "mac": "00:1A:7D:DA:71:13", "rssi": random.randint(-55, -25), "type": "OBD2_Dongle", "honeywell": True},
256
+ {"name": "BMS-Telemetry-Sensor", "mac": "5C:CF:7F:C2:AA:BB", "rssi": random.randint(-65, -35), "type": "BMS_Sensor", "honeywell": True},
257
+ {"name": "EV-Charger-CCS2", "mac": "AC:CF:85:3D:12:44", "rssi": random.randint(-70, -40), "type": "Charger", "honeywell": False},
258
+ {"name": "Thermal-Probe-BLE", "mac": "AA:BB:CC:DD:EE:FF", "rssi": random.randint(-60, -30), "type": "Thermal", "honeywell": True},
259
+ {"name": "Isolation-Monitor", "mac": "11:22:33:44:55:66", "rssi": random.randint(-75, -45), "type": "Isolation", "honeywell": False},
260
+ ]
261
+ return devices
262
+
263
+ def get_telemetry(self) -> Dict[str, Any]:
264
+ return {
265
+ "source": "BLE_LE_Encrypted",
266
+ "encryption": "AES-256-GCM",
267
+ "key_id": self.aes_key_id,
268
+ "e2e_active": self.encryption_active,
269
+ "voltage_pack_v": round(random.uniform(350, 405), 2),
270
+ "current_a": round(random.uniform(-50, 150), 2),
271
+ "power_kw": round(random.uniform(-20, 60), 2),
272
+ "temp_max_c": round(random.uniform(25, 45), 1),
273
+ "temp_min_c": round(random.uniform(15, 30), 1),
274
+ "isolation_mohm": round(random.uniform(1.0, 5.0), 3),
275
+ "timestamp": datetime.datetime.now().isoformat(),
276
+ }
277
+
278
+
279
+ class EmobilityAiAgent:
280
+ """AI Agent with MCP architecture and HuggingFace TinyAgent"""
281
+
282
+ def __init__(self):
283
+ self.registered_tools: List[McpTool] = []
284
+ self.conversation_history: List[Dict[str, str]] = []
285
+ self._register_default_tools()
286
+
287
+ def _register_default_tools(self):
288
+ default_tools = [
289
+ McpTool(id="get_bms_status", name="BMS Telemetrie-Abtastung", description="Analysiert Zellspannungen und SOH des Hochvoltspeichers", category="diagnostics", icon="🔋"),
290
+ McpTool(id="run_sys_audit", name="uHAL Bus-Audit", description="Prüft USB-C Transportintegrität & Paketpuffer", category="system", icon="🔍"),
291
+ McpTool(id="obd_scan", name="OBD-II Diagnose", description="Führt vollständige OBD-II Fahrzeugdiagnose durch", category="diagnostics", icon="🚗"),
292
+ McpTool(id="ble_telemetry", name="BLE Telemetrie-Stream", description="Liest Echtzeit-Sensordaten über verschlüsselte BLE-Verbindung", category="connectivity", icon="📡"),
293
+ McpTool(id="nfc_identify", name="NFC Fahrzeug-Identifikation", description="Identifiziert Fahrzeug über NFC Smart-Card Tap", category="connectivity", icon="💳"),
294
+ McpTool(id="wifi_diag", name="WiFi Netzwerk-Diagnose", description="Analysiert WiFi-Verbindungsqualität und Netzwerkparameter", category="connectivity", icon="📶"),
295
+ McpTool(id="barcode_scan", name="Barcode Scanner", description="Löst Honeywell N6700 Hardware-Barcode-Scan aus", category="hardware", icon="📷"),
296
+ McpTool(id="lib_sync", name="Bibliotheks-Synchronisation", description="Synchronisiert alle Honeywell-Bibliotheken und Datenbanken lokal", category="system", icon="🔄"),
297
+ McpTool(id="e2e_encrypt", name="E2E Verschlüsselung-Check", description="Verifiziert End-to-End Verschlüsselung aller Telemetriekanäle", category="security", icon="🔐"),
298
+ McpTool(id="factory_reset", name="Factory Reset", description="Sicherer Factory Reset mit Hardware-Token-Verifikation", category="system", icon="⚠️"),
299
+ ]
300
+ self.registered_tools = default_tools
301
+
302
+ def register_tool(self, tool: McpTool):
303
+ self.registered_tools.append(tool)
304
+
305
+ def get_tools_by_category(self) -> Dict[str, List[McpTool]]:
306
+ categories: Dict[str, List[McpTool]] = {}
307
+ for tool in self.registered_tools:
308
+ if tool.category not in categories:
309
+ categories[tool.category] = []
310
+ categories[tool.category].append(tool)
311
+ return categories
312
+
313
+ async def ask_agent(self, prompt: str, context: str = "") -> str:
314
+ self.conversation_history.append({"role": "user", "content": prompt})
315
+
316
+ # Simulated AI response with context awareness
317
+ prompt_lower = prompt.lower()
318
+ if any(kw in prompt_lower for kw in ["batterie", "bms", "soc", "soh", "zellspannung"]):
319
+ response = (
320
+ "🔋 **BMS Diagnose-Ergebnis:**\n\n"
321
+ "- **State of Health (SOH):** 96.8% — Nominal\n"
322
+ "- **State of Charge (SOC):** 72.4% — Normal\n"
323
+ "- **Zellspannungs-Delta (ΔV):** 12 mV — Innerhalb Toleranz (<30mV)\n"
324
+ "- **Isolationswiderstand:** 1.400 kΩ — Sicher (>1 kΩ)\n"
325
+ "- **Temperatur-Spread:** 4.2°C — Normal\n\n"
326
+ "✅ Keine Anomalie erkannt. Hochvoltspeicher ist in gutem Zustand.\n"
327
+ "📋 Empfehlung: Nächste Kalibrierung in 6 Monaten."
328
+ )
329
+ elif any(kw in prompt_lower for kw in ["obd", "fehlercode", "dtc", "diagnose"]):
330
+ response = (
331
+ "🚗 **OBD-II Diagnose-Ergebnis:**\n\n"
332
+ "- **Protokoll:** ISO 15765-4 (CAN 500k)\n"
333
+ "- **Fehlercodes (DTCs):** Keine aktiven DTCs\n"
334
+ "- ** readiness Monitors:** Alle bestanden\n"
335
+ "- **Emission-Status:** Bereit\n\n"
336
+ "✅ Fahrzeug-ECU meldet keinen Fehler."
337
+ )
338
+ elif any(kw in prompt_lower for kw in ["verschlüsselung", "encryption", "sicherheit", "security"]):
339
+ response = (
340
+ "🔐 **Sicherheits-Audit:**\n\n"
341
+ "- **E2E Verschlüsselung:** AES-256-GCM aktiv\n"
342
+ "- **Hardware-Root-of-Trust:** Honeywell CT45P verifiziert\n"
343
+ "- **BLE-Encryption:** Verschlüsselte GATT-Charakteristiken\n"
344
+ "- **USB-C:** TLS 1.3 auf serieller Verbindung\n"
345
+ "- **Token-Status:** SIL-2 validiert\n\n"
346
+ "✅ Alle Kommunikationskanäle sind verschlüsselt."
347
+ )
348
+ elif any(kw in prompt_lower for kw in ["reset", "werkszustand", "factory"]):
349
+ response = (
350
+ "⚠️ **Factory Reset Anforderung:**\n\n"
351
+ "Für Factory Reset wird **SIL-Level 3+** benötigt.\n"
352
+ "1. Hardware-Token verifizieren\n"
353
+ "2. Backup erstellen\n"
354
+ "3. Reset ausführen\n"
355
+ "4. Post-Reset-Verifikation\n\n"
356
+ "📋 Verwende den Factory Reset Tab im System-Panel."
357
+ )
358
+ else:
359
+ response = (
360
+ f"🤖 **KI-Antwort:**\n\n"
361
+ f"Anfrage analysiert: '{prompt[:60]}...'\n\n"
362
+ f"Verfügbare MCP-Tools: {len(self.registered_tools)}\n"
363
+ f"Aktive Verbindungen: BLE + USB-C Hybrid\n"
364
+ f"Hardware: Honeywell CT45P XP (Android 11)\n\n"
365
+ "💡 Tipp: Fragen zu Batterie/BMS, OBD-Diagnose, Verschlüsselung oder Factory Reset werden kontextbezogen beantwortet."
366
+ )
367
+
368
+ self.conversation_history.append({"role": "assistant", "content": response})
369
+ return response
370
+
371
+
372
+ class AuditLogger:
373
+ """Central audit logging system"""
374
+
375
+ def __init__(self):
376
+ self.entries: List[AuditEntry] = []
377
+
378
+ def log(self, event_type: str, severity: str, user_id: str, message: str, details: Dict = None):
379
+ entry = AuditEntry(
380
+ timestamp=datetime.datetime.now().isoformat(),
381
+ event_type=event_type,
382
+ severity=severity,
383
+ user_id=user_id,
384
+ message=message,
385
+ details=details or {},
386
+ )
387
+ self.entries.append(entry)
388
+ if len(self.entries) > 500:
389
+ self.entries = self.entries[-500:]
390
+
391
+ def get_recent(self, count: int = 50) -> List[Dict]:
392
+ return [asdict(e) for e in self.entries[-count:]]
393
+
394
+
395
+ class HardwareTokenManager:
396
+ """Hardware Root-of-Trust Token Manager"""
397
+
398
+ def __init__(self):
399
+ self.hardware_root_id = "HWR-" + hashlib.sha256(b"honeywell_ct45p_root").hexdigest()[:16].upper()
400
+ self.device_root_id = "DEV-" + hashlib.sha256(b"ct45p_device").hexdigest()[:16].upper()
401
+ self.verified_tokens: Dict[str, HardwareToken] = {}
402
+
403
+ def create_token(self, permissions: List[str], sil_level: int = 1) -> HardwareToken:
404
+ now = datetime.datetime.now()
405
+ token = HardwareToken(
406
+ token_id="TKN-" + hashlib.sha256(str(now.timestamp()).encode()).hexdigest()[:12].upper(),
407
+ hardware_id=self.hardware_root_id,
408
+ device_id=self.device_root_id,
409
+ issued_at=now.isoformat(),
410
+ expires_at=(now + datetime.timedelta(hours=8)).isoformat(),
411
+ permissions=permissions,
412
+ sil_level=sil_level,
413
+ )
414
+ self.verified_tokens[token.token_id] = token
415
+ return token
416
+
417
+ def verify_token(self, token: HardwareToken) -> bool:
418
+ if not token.is_valid():
419
+ return False
420
+ if token.hardware_id != self.hardware_root_id:
421
+ return False
422
+ if token.device_id != self.device_root_id:
423
+ return False
424
+ return True
425
+
426
+
427
+ # ============================================================
428
+ # GLOBAL SERVICE INSTANCES
429
+ # ============================================================
430
+
431
+ honeywell_sdk = HoneywellSdkService()
432
+ uhal_diag = UhalHardwareDiagnostics()
433
+ ble_manager = SecureBleLeManager()
434
+ ai_agent = EmobilityAiAgent()
435
+ audit_logger = AuditLogger()
436
+ token_manager = HardwareTokenManager()
437
+
438
+ # Enable UHAL permissive mode on startup
439
+ uhal_diag.enable_permissive_mode()
440
+ audit_logger.log("system", "info", "system", "UHAL Permissive Mode aktiviert")
441
+ audit_logger.log("system", "info", "system", "Honeywell NDK/SDK/AgentSDK/PowerTools geladen")
442
+
443
+
444
+ # ============================================================
445
+ # HANDLER FUNCTIONS
446
+ # ============================================================
447
+
448
+ def handle_barcode_scan():
449
+ result = honeywell_sdk.scan_barcode()
450
+ audit_logger.log("hardware", "info", "scanner", f"Barcode gescannt: {result['barcode']}", result)
451
+ return json.dumps(result, indent=2, ensure_ascii=False)
452
+
453
+ def handle_obd_diagnosis():
454
+ result = honeywell_sdk.get_obd_data()
455
+ audit_logger.log("diagnostics", "info", "obd_service", "OBD-II Diagnose durchgeführt", result)
456
+ return json.dumps(result, indent=2, ensure_ascii=False)
457
+
458
+ def handle_wifi_diag():
459
+ result = honeywell_sdk.get_wifi_diagnostics()
460
+ return json.dumps(result, indent=2, ensure_ascii=False)
461
+
462
+ def handle_lib_sync():
463
+ result = honeywell_sdk.sync_local_libraries()
464
+ audit_logger.log("system", "info", "agent_sdk", "Bibliotheken synchronisiert", result)
465
+ return json.dumps(result, indent=2, ensure_ascii=False)
466
+
467
+ def handle_uhal_audit():
468
+ result = uhal_diag.get_bus_audit()
469
+ audit_logger.log("system", "info", "uhal_manager", "Bus-Audit durchgeführt", result)
470
+ return json.dumps(result, indent=2, ensure_ascii=False)
471
+
472
+ def handle_ble_scan():
473
+ devices = ble_manager.scan_peripherals()
474
+ audit_logger.log("connectivity", "info", "ble_le", f"BLE Scan: {len(devices)} Geräte gefunden")
475
+ return json.dumps(devices, indent=2, ensure_ascii=False)
476
+
477
+ def handle_ble_telemetry():
478
+ result = ble_manager.get_telemetry()
479
+ return json.dumps(result, indent=2, ensure_ascii=False)
480
+
481
+ def handle_usb_toggle(attached):
482
+ uhal_diag.set_usb_dongle(attached)
483
+ source = "USB-C Hardware" if attached else "BLE LE"
484
+ audit_logger.log("connectivity", "info", "hybrid_mgr", f"Datenquelle gewechselt: {source}")
485
+ return f"✅ Aktive Datenquelle: **{source}**\nUSB-Dongle: {'Angesteckt' if attached else 'Entfernt'}"
486
+
487
+ def handle_nfc_scan():
488
+ tag = NfcTagData(
489
+ uid="04:D2:AA:BB:CC:55:01",
490
+ tag_type=NfcTagType.NTAG215.value,
491
+ ndef_records={
492
+ "uhal_device_id": "HON-STEUERGERAET-BT60",
493
+ "uhal_action": "IDENTIFY",
494
+ "vehicle_vin": "WBA3E5G0C234567",
495
+ "work_order": "WO-2024-00847",
496
+ },
497
+ scanned_at=datetime.datetime.now().isoformat(),
498
+ )
499
+ result = asdict(tag)
500
+ audit_logger.log("connectivity", "info", "nfc_sensor", f"NFC Tag gelesen: {tag.uhal_device_id}", result)
501
+ return json.dumps(result, indent=2, ensure_ascii=False)
502
+
503
+ def handle_mcp_execute(tool_id: str):
504
+ tools_map = {t.id: t for t in ai_agent.registered_tools}
505
+ if tool_id not in tools_map:
506
+ return f"❌ Tool '{tool_id}' nicht gefunden"
507
+
508
+ tool = tools_map[tool_id]
509
+
510
+ # Execute tool with simulated results
511
+ if tool_id == "get_bms_status":
512
+ result = f"SoH: 96.8%, ΔV: 12mV, Isolationswiderstand: 1400kΩ. Nominal."
513
+ elif tool_id == "run_sys_audit":
514
+ audit = uhal_diag.get_bus_audit()
515
+ result = f"Integrität: {audit['integrity_percent']}%, Pufferverlust: {audit['buffer_loss_percent']}%, Signal: {audit['signal_quality']}"
516
+ elif tool_id == "obd_scan":
517
+ obd = honeywell_sdk.get_obd_data()
518
+ result = f"VIN: {obd['vin']}, SOC: {obd['soc']}%, SOH: {obd['soh']}%, DTCs: {obd['dtcs']}"
519
+ elif tool_id == "ble_telemetry":
520
+ tel = ble_manager.get_telemetry()
521
+ result = f"Pack: {tel['voltage_pack_v']}V, {tel['current_a']}A, E2E: {tel['encryption']}"
522
+ elif tool_id == "nfc_identify":
523
+ result = "UID: 04:D2:AA:BB:CC:55:01, Device: HON-STEUERGERAET-BT60"
524
+ elif tool_id == "wifi_diag":
525
+ wifi = honeywell_sdk.get_wifi_diagnostics()
526
+ result = f"SSID: {wifi['ssid']}, RSSI: {wifi['rssi_dbm']}dBm, Speed: {wifi['link_speed_mbps']}Mbps"
527
+ elif tool_id == "barcode_scan":
528
+ bc = honeywell_sdk.scan_barcode()
529
+ result = f"Code: {bc['barcode']}, Format: {bc['format']}"
530
+ elif tool_id == "lib_sync":
531
+ result = "Alle Honeywell-Bibliotheken und Datenbanken synchronisiert und lokal gesichert."
532
+ elif tool_id == "e2e_encrypt":
533
+ result = "AES-256-GCM auf allen Kanälen aktiv. Hardware-Root-of-Trust verifiziert."
534
+ elif tool_id == "factory_reset":
535
+ result = "⚠️ Factory Reset erfordert SIL-Level 3+ Hardware-Token. Bitte System-Panel verwenden."
536
+ else:
537
+ result = f"Tool '{tool.name}' ausgeführt."
538
+
539
+ audit_logger.log("mcp", "info", "mcp_pipeline", f"MCP Tool ausgeführt: {tool.name}", {"tool_id": tool_id, "result": result})
540
+ return f"{tool.icon} **{tool.name}**\n\n{result}"
541
+
542
+ def handle_ai_chat(message, history):
543
+ # Convert gradio history format
544
+ response = asyncio.run(ai_agent.ask_agent(message))
545
+ audit_logger.log("ai_agent", "info", "tinyagent", f"KI-Anfrage: {message[:50]}...")
546
+ return response
547
+
548
+ def handle_create_token(permissions, sil_level):
549
+ perms = [p.strip() for p in permissions.split(",") if p.strip()]
550
+ token = token_manager.create_token(perms, sil_level)
551
+ audit_logger.log("security", "info", "token_mgr", f"Token erstellt: {token.token_id}", asdict(token))
552
+ return json.dumps(asdict(token), indent=2, ensure_ascii=False)
553
+
554
+ def handle_verify_token(token_json):
555
+ try:
556
+ data = json.loads(token_json)
557
+ token = HardwareToken(**data)
558
+ is_valid = token_manager.verify_token(token)
559
+ if is_valid:
560
+ 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}"
561
+ else:
562
+ return "❌ Token **UNGÜLTIG** — Hardware-ID Mismatch oder abgelaufen"
563
+ except Exception as e:
564
+ return f"❌ Fehler bei Token-Verifikation: {str(e)}"
565
+
566
+ def handle_factory_reset(level, reason, backup):
567
+ sil_map = {"SIL1 (Diagnose)": 1, "SIL2 (Konfiguration)": 2, "SIL3 (Firmware)": 3, "SIL4 (Sicherheitskritisch)": 4}
568
+ level_map = {"Soft (App-Daten)": ResetLevel.SOFT, "Standard (App+Cache)": ResetLevel.STANDARD, "Hard (Alles außer MDM)": ResetLevel.HARD, "Factory (Vollständig)": ResetLevel.FACTORY}
569
+
570
+ reset_lvl = level_map.get(level, ResetLevel.SOFT)
571
+ required_sil = 3 if reset_lvl in [ResetLevel.HARD, ResetLevel.FACTORY] else 1
572
+
573
+ token = token_manager.create_token(
574
+ permissions=[f"level_{i}" for i in range(1, required_sil + 1)],
575
+ sil_level=required_sil,
576
+ )
577
+
578
+ result = f"""⚠️ **Factory Reset Protokoll**
579
+
580
+ **Reset-Level:** {reset_lvl.value.upper()}
581
+ **Erforderliches SIL-Level:** {required_sil}
582
+ **Hardware-Token:** {token.token_id}
583
+ **Backup:** {'Ja' if backup else 'Nein'}
584
+ **Grund:** {reason}
585
+
586
+ **Ausführungsschritte:**
587
+ 1. ✅ Token verifiziert (SIL-{required_sil})
588
+ 2. {"✅ Backup erstellt" if backup else "⏭️ Backup übersprungen"}
589
+ 3. ✅ Reset ausgeführt: {reset_lvl.value}
590
+ 4. ✅ Post-Reset-Verifikation bestanden
591
+
592
+ **Dauer:** 2.3 Sekunden
593
+ **Status:** ERFOLGREICH"""
594
+
595
+ audit_logger.log("system", "critical", "factory_reset", f"Factory Reset: {reset_lvl.value}", {"level": reset_lvl.value, "reason": reason})
596
+ return result
597
+
598
+ def handle_get_audit_log():
599
+ entries = audit_logger.get_recent(30)
600
+ if not entries:
601
+ return "Keine Audit-Einträge vorhanden."
602
+ lines = []
603
+ for e in entries:
604
+ icon = {"info": "ℹ️", "warning": "⚠️", "critical": "🔴", "error": "❌"}.get(e["severity"], "•")
605
+ lines.append(f"{icon} `{e['timestamp'][:19]}` [{e['severity'].upper()}] {e['event_type']} — {e['message']}")
606
+ return "\n".join(lines)
607
+
608
+ def handle_get_system_status():
609
+ return json.dumps({
610
+ "device": honeywell_sdk.device_id,
611
+ "firmware": honeywell_sdk.firmware_version,
612
+ "android": honeywell_sdk.android_version,
613
+ "ndk_loaded": honeywell_sdk.ndk_loaded,
614
+ "sdk_loaded": honeywell_sdk.sdk_loaded,
615
+ "uhal_mode": "permissive" if uhal_diag.permissive_mode else "restricted",
616
+ "usb_dongle": uhal_diag.usb_dongle_attached,
617
+ "active_source": uhal_diag.active_source.value,
618
+ "ble_encryption": ble_manager.encryption_active,
619
+ "mcp_tools": len(ai_agent.registered_tools),
620
+ "audit_entries": len(audit_logger.entries),
621
+ "hardware_root_id": token_manager.hardware_root_id,
622
+ "device_root_id": token_manager.device_root_id,
623
+ }, indent=2, ensure_ascii=False)
624
+
625
+ def handle_add_mcp_tool(tool_id, tool_name, tool_desc, tool_category):
626
+ if not tool_id or not tool_name:
627
+ return "❌ Tool-ID und Name sind erforderlich.", gr.Dropdown(choices=[t.id for t in ai_agent.registered_tools])
628
+
629
+ existing_ids = [t.id for t in ai_agent.registered_tools]
630
+ if tool_id in existing_ids:
631
+ return f"❌ Tool-ID '{tool_id}' existiert bereits.", gr.Dropdown(choices=existing_ids)
632
+
633
+ new_tool = McpTool(id=tool_id, name=tool_name, description=tool_desc, category=tool_category, icon="⚡")
634
+ ai_agent.register_tool(new_tool)
635
+ audit_logger.log("mcp", "info", "mcp_registry", f"Neues MCP-Tool registriert: {tool_name}")
636
+ updated_ids = [t.id for t in ai_agent.registered_tools]
637
+ return f"✅ Tool '{tool_name}' ({tool_id}) in Kategorie '{tool_category}' registriert.", gr.Dropdown(choices=updated_ids)
638
+
639
+
640
+ # ============================================================
641
+ # GRADIO 6 APPLICATION
642
+ # ============================================================
643
+
644
+ custom_theme = gr.themes.Soft(
645
+ primary_hue="red",
646
+ secondary_hue="orange",
647
+ neutral_hue="slate",
648
+ font=gr.themes.GoogleFont("Inter"),
649
+ text_size="md",
650
+ spacing_size="md",
651
+ radius_size="md",
652
+ ).set(
653
+ button_primary_background_fill="*primary_600",
654
+ button_primary_background_fill_hover="*primary_700",
655
+ block_title_text_weight="600",
656
+ body_background_fill="#0a0a0a",
657
+ block_background_fill="#141414",
658
+ block_border_color="#2a2a2a",
659
+ )
660
+
661
+ with gr.Blocks() as demo:
662
+
663
+ gr.Markdown(
664
+ """
665
+ # 🔧 Honeywell CT45P XP — E-Mobility Service Werkstatt
666
+ ### UHAL Edge Workspace | Android 11 | NDK/SDK/AgentSDK/PowerTools
667
+
668
+ [Built with anycoder](https://huggingface.co/spaces/akhaliq/anycoder)
669
+ """
670
+ )
671
+
672
+ # System status bar
673
+ with gr.Row():
674
+ status_box = gr.JSON(label="System Status", value=json.loads(handle_get_system_status()), height=120)
675
+
676
+ with gr.Tabs():
677
+
678
+ # ============================================================
679
+ # TAB 1: HARDWARE DIAGNOSTICS
680
+ # ============================================================
681
+ with gr.Tab("🔍 Hardware Diagnose"):
682
+ gr.Markdown("### Honeywell Mobility SDK & PowerTools — Echtzeit-Diagnose")
683
+
684
+ with gr.Row():
685
+ with gr.Column(scale=1):
686
+ gr.Markdown("#### 📷 Barcode Scanner (N6700)")
687
+ scan_btn = gr.Button("Hardware-Scan auslösen", variant="primary", icon="camera")
688
+ scan_result = gr.Code(language="json", label="Scan-Ergebnis", lines=8)
689
+
690
+ with gr.Column(scale=1):
691
+ gr.Markdown("#### 🚗 OBD-II Diagnose (PowerTools)")
692
+ obd_btn = gr.Button("OBD-II Diagnose starten", variant="primary", icon="car")
693
+ obd_result = gr.Code(language="json", label="OBD-Ergebnis", lines=8)
694
+
695
+ with gr.Row():
696
+ with gr.Column(scale=1):
697
+ gr.Markdown("#### 📶 WiFi Diagnose")
698
+ wifi_btn = gr.Button("WiFi-Status prüfen", variant="secondary")
699
+ wifi_result = gr.Code(language="json", label="WiFi-Ergebnis", lines=6)
700
+
701
+ with gr.Column(scale=1):
702
+ gr.Markdown("#### 🔄 Bibliotheks-Sync")
703
+ sync_btn = gr.Button("Honeywell Libs synchronisieren", variant="secondary")
704
+ sync_result = gr.Code(language="json", label="Sync-Ergebnis", lines=6)
705
+
706
+ with gr.Row():
707
+ with gr.Column(scale=1):
708
+ gr.Markdown("#### 💳 NFC Smart Card")
709
+ nfc_btn = gr.Button("NFC Tap-to-Identify", variant="primary", icon="credit_card")
710
+ nfc_result = gr.Code(language="json", label="NFC-Ergebnis", lines=10)
711
+
712
+ with gr.Column(scale=1):
713
+ gr.Markdown("#### 🔍 uHAL Bus-Audit")
714
+ audit_btn = gr.Button("Bus-Integrität prüfen", variant="secondary")
715
+ audit_result = gr.Code(language="json", label="Audit-Ergebnis", lines=10)
716
+
717
+ scan_btn.click(handle_barcode_scan, outputs=scan_result)
718
+ obd_btn.click(handle_obd_diagnosis, outputs=obd_result)
719
+ wifi_btn.click(handle_wifi_diag, outputs=wifi_result)
720
+ sync_btn.click(handle_lib_sync, outputs=sync_result)
721
+ nfc_btn.click(handle_nfc_scan, outputs=nfc_result)
722
+ audit_btn.click(handle_uhal_audit, outputs=audit_result)
723
+
724
+ # ============================================================
725
+ # TAB 2: BLE & CONNECTIVITY
726
+ # ============================================================
727
+ with gr.Tab("📡 BLE LE & Konnektivität"):
728
+ gr.Markdown("### BLE 6.0 LE — E2E Verschlüsselte Telemetrie & USB-C Hybrid")
729
+
730
+ with gr.Row():
731
+ with gr.Column(scale=1):
732
+ gr.Markdown("#### 🔵 BLE Peripheral Scan")
733
+ ble_scan_btn = gr.Button("BLE LE Scan starten", variant="primary", icon="bluetooth")
734
+ ble_scan_result = gr.Code(language="json", label="BLE Geräte", lines=15)
735
+
736
+ with gr.Column(scale=1):
737
+ gr.Markdown("#### 📡 Echtzeit-Telemetrie (Verschlüsselt)")
738
+ ble_tel_btn = gr.Button("Telemetrie abrufen (AES-256-GCM)", variant="primary")
739
+ ble_tel_result = gr.Code(language="json", label="Telemetrie-Daten", lines=12)
740
+
741
+ with gr.Row():
742
+ with gr.Column(scale=1):
743
+ gr.Markdown("#### 🔌 USB-C Hybrid Hot-Swap")
744
+ usb_toggle = gr.Checkbox(label="USB-C OBD2-Dongle angesteckt", value=False)
745
+ usb_status = gr.Textbox(label="Datenquelle", lines=3, value="Aktive Datenquelle: **BLE LE**\nUSB-Dongle: Entfernt")
746
+
747
+ with gr.Column(scale=1):
748
+ gr.Markdown("#### 🔐 E2E Verschlüsselung")
749
+ gr.JSON(
750
+ value={
751
+ "algorithm": "AES-256-GCM",
752
+ "key_derivation": "HKDF-SHA256",
753
+ "key_id": ble_manager.aes_key_id,
754
+ "channels": ["BLE_GATT", "USB_C_SERIAL", "NFC_NDEF"],
755
+ "status": "active",
756
+ "hardware_root": token_manager.hardware_root_id,
757
+ },
758
+ label="Verschlüsselungs-Status",
759
+ )
760
+
761
+ ble_scan_btn.click(handle_ble_scan, outputs=ble_scan_result)
762
+ ble_tel_btn.click(handle_ble_telemetry, outputs=ble_tel_result)
763
+ usb_toggle.change(handle_usb_toggle, inputs=usb_toggle, outputs=usb_status)
764
+
765
+ # ============================================================
766
+ # TAB 3: MCP PIPELINE
767
+ # ============================================================
768
+ with gr.Tab("🔧 MCP Pipeline"):
769
+ gr.Markdown("### MCP Tool-Registry & Drag-Integration — Diagnose-Pipeline Konstruktor")
770
+
771
+ with gr.Row():
772
+ with gr.Column(scale=2):
773
+ gr.Markdown("#### 📋 Verfügbare MCP-Tools")
774
+ mcp_tool_select = gr.Dropdown(
775
+ choices=[t.id for t in ai_agent.registered_tools],
776
+ label="Tool auswählen",
777
+ info="Wähle ein MCP-Tool zur Ausführung",
778
+ )
779
+ mcp_execute_btn = gr.Button("Tool ausführen", variant="primary", icon="play")
780
+ mcp_result = gr.Textbox(label="Ausführungsergebnis", lines=6, max_lines=15)
781
+
782
+ with gr.Column(scale=3):
783
+ gr.Markdown("#### 🗂️ Tool-Kategorien")
784
+ categories = ai_agent.get_tools_by_category()
785
+ cat_data = []
786
+ for cat, tools in categories.items():
787
+ for t in tools:
788
+ cat_data.append([t.icon, t.id, t.name, t.description, cat])
789
+
790
+ gr.Dataframe(
791
+ value=cat_data,
792
+ headers=["", "ID", "Name", "Beschreibung", "Kategorie"],
793
+ label="MCP Tool-Registry",
794
+ interactive=False,
795
+ column_widths=[40, 150, 200, 300, 120],
796
+ height=350,
797
+ )
798
+
799
+ gr.Markdown("#### ➕ Eigenes MCP-Tool registrieren")
800
+ with gr.Row():
801
+ new_tool_id = gr.Textbox(label="Tool-ID", placeholder="z.B. custom_ev_check")
802
+ new_tool_name = gr.Textbox(label="Name", placeholder="z.B. EV Fahrzeug-Check")
803
+ new_tool_desc = gr.Textbox(label="Beschreibung", placeholder="z.B. Prüft Fahrzeug-Status")
804
+ new_tool_cat = gr.Dropdown(
805
+ choices=["diagnostics", "connectivity", "system", "security", "hardware", "custom"],
806
+ label="Kategorie",
807
+ value="custom",
808
+ )
809
+
810
+ add_tool_btn = gr.Button("Tool registrieren", variant="secondary")
811
+ add_tool_result = gr.Textbox(label="Registrierungs-Status", lines=2)
812
+
813
+ mcp_execute_btn.click(handle_mcp_execute, inputs=mcp_tool_select, outputs=mcp_result)
814
+ add_tool_btn.click(
815
+ handle_add_mcp_tool,
816
+ inputs=[new_tool_id, new_tool_name, new_tool_desc, new_tool_cat],
817
+ outputs=[add_tool_result, mcp_tool_select],
818
+ )
819
+
820
+ # ============================================================
821
+ # TAB 4: AI AGENT
822
+ # ============================================================
823
+ with gr.Tab("🤖 KI Agent (TinyAgent)"):
824
+ gr.Markdown("### HuggingFace TinyAgent — Kontextbezogene E-Mobility Diagnose-KI")
825
+
826
+ with gr.Row():
827
+ with gr.Column(scale=3):
828
+ ai_chat = gr.ChatInterface(
829
+ fn=handle_ai_chat,
830
+ title="E-Mobility KI-Assistent",
831
+ description="Fragen zu Batterie/BMS, OBD-Diagnose, Verschlüsselung, Factory Reset und mehr.",
832
+ examples=[
833
+ "Batterie-Anomalieprüfung anfordern",
834
+ "OBD-II Fehlercodes auslesen",
835
+ "E2E Verschlüsselung verifizieren",
836
+ "Factory Reset durchführen",
837
+ "BMS Zellspannungs-Analyse",
838
+ "Isolationswiderstand prüfen",
839
+ ],
840
+ cache_examples=False,
841
+ )
842
+
843
+ with gr.Column(scale=2):
844
+ gr.Markdown("#### 🧠 Agent-Kontext")
845
+ gr.JSON(
846
+ value={
847
+ "model": "meta-llama/Llama-2-7b-chat-hf (Edge)",
848
+ "architecture": "MCP (Model Context Protocol)",
849
+ "tools_available": len(ai_agent.registered_tools),
850
+ "context_injection": "BMS/OBD Telemetrie",
851
+ "hardware_binding": "Honeywell CT45P XP",
852
+ "encryption": "E2E AES-256-GCM",
853
+ "offline_capable": True,
854
+ "huggingface_integration": True,
855
+ },
856
+ label="Agent-Konfiguration",
857
+ )
858
+
859
+ gr.Markdown("#### 📊 Verfügbare MCP-Kontexte")
860
+ context_tools = []
861
+ for t in ai_agent.registered_tools:
862
+ context_tools.append([t.icon, t.name, t.category])
863
+ gr.Dataframe(
864
+ value=context_tools,
865
+ headers=["", "Tool", "Kategorie"],
866
+ label="KI-Kontext-Quellen",
867
+ interactive=False,
868
+ height=300,
869
+ )
870
+
871
+ # ============================================================
872
+ # TAB 5: SECURITY & TOKENS
873
+ # ============================================================
874
+ with gr.Tab("🔐 Sicherheit & Tokens"):
875
+ gr.Markdown("### Hardware-Root-of-Trust & SIL-Level Authentifizierung")
876
+
877
+ with gr.Row():
878
+ with gr.Column(scale=1):
879
+ gr.Markdown("#### 🏛️ Hardware-Root-of-Trust")
880
+ gr.JSON(
881
+ value={
882
+ "hardware_root_id": token_manager.hardware_root_id,
883
+ "device_root_id": token_manager.device_root_id,
884
+ "device": honeywell_sdk.device_id,
885
+ "firmware": honeywell_sdk.firmware_version,
886
+ "android": honeywell_sdk.android_version,
887
+ "uhal_mode": "permissive",
888
+ },
889
+ label="Root-of-Trust Identität",
890
+ )
891
+
892
+ with gr.Column(scale=1):
893
+ gr.Markdown("#### ➕ Token erstellen")
894
+ perm_input = gr.Textbox(
895
+ label="Berechtigungen (komma-getrennt)",
896
+ value="level_1, level_2",
897
+ placeholder="level_1, level_2, level_3, level_4",
898
+ )
899
+ sil_input = gr.Slider(
900
+ minimum=1, maximum=4, value=1, step=1,
901
+ label="SIL-Level",
902
+ info="1=Diagnose, 2=Konfiguration, 3=Firmware, 4=Sicherheitskritisch",
903
+ )
904
+ create_token_btn = gr.Button("Hardware-Token erstellen", variant="primary")
905
+ token_result = gr.Code(language="json", label="Erstelltes Token", lines=12)
906
+
907
+ with gr.Row():
908
+ with gr.Column():
909
+ gr.Markdown("#### 🔍 Token verifizieren")
910
+ verify_input = gr.Code(language="json", label="Token JSON einfügen", lines=10, placeholder="Füge ein Token JSON ein...")
911
+ verify_btn = gr.Button("Token verifizieren", variant="secondary")
912
+ verify_result = gr.Textbox(label="Verifikationsergebnis", lines=5)
913
+
914
+ create_token_btn.click(handle_create_token, inputs=[perm_input, sil_input], outputs=token_result)
915
+ verify_btn.click(handle_verify_token, inputs=verify_input, outputs=verify_result)
916
+
917
+ # ============================================================
918
+ # TAB 6: FACTORY RESET
919
+ # ============================================================
920
+ with gr.Tab("⚠️ Factory Reset"):
921
+ gr.Markdown("### Sicherer Factory Reset — Hardware-Authentifiziert & Audit-Logged")
922
+ gr.Markdown("> ⚠️ **WARNUNG:** Factory Reset erfordert SIL-Level 3+ und erstellt automatisch ein Backup.")
923
+
924
+ with gr.Row():
925
+ with gr.Column(scale=1):
926
+ reset_level = gr.Radio(
927
+ choices=["Soft (App-Daten)", "Standard (App+Cache)", "Hard (Alles außer MDM)", "Factory (Vollständig)"],
928
+ label="Reset-Level",
929
+ value="Soft (App-Daten)",
930
+ )
931
+ reset_reason = gr.Textbox(label="Grund für Reset", placeholder="z.B. Fahrzeug-Übergabe, Fehlerbehebung...", lines=2)
932
+ reset_backup = gr.Checkbox(label="Backup vor Reset erstellen", value=True)
933
+ reset
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ dataclasses
2
+ enum
3
+ gradio>=6.0.2