backend.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  1. from PySide6.QtCore import QObject, Signal, Property, Slot, QTimer
  2. from PySide6.QtQml import QmlElement
  3. from PySide6.QtWebSockets import QWebSocket
  4. from PySide6.QtNetwork import QAbstractSocket
  5. import aiohttp
  6. import asyncio
  7. import json
  8. import subprocess
  9. import threading
  10. import time
  11. from pathlib import Path
  12. import os
  13. QML_IMPORT_NAME = "DuneWeaver"
  14. QML_IMPORT_MAJOR_VERSION = 1
  15. @QmlElement
  16. class Backend(QObject):
  17. """Backend controller for API and WebSocket communication"""
  18. # Constants
  19. SETTINGS_FILE = "touch_settings.json"
  20. DEFAULT_SCREEN_TIMEOUT = 300 # 5 minutes in seconds
  21. # Predefined timeout options (in seconds)
  22. TIMEOUT_OPTIONS = {
  23. "30 seconds": 30,
  24. "1 minute": 60,
  25. "5 minutes": 300,
  26. "10 minutes": 600,
  27. "Never": 0 # 0 means never timeout
  28. }
  29. # Predefined speed options
  30. SPEED_OPTIONS = {
  31. "50": 50,
  32. "100": 100,
  33. "200": 200,
  34. "300": 300,
  35. "500": 500
  36. }
  37. # Predefined pause between patterns options (in seconds)
  38. PAUSE_OPTIONS = {
  39. "0s": 0, # No pause
  40. "1 min": 60, # 1 minute
  41. "5 min": 300, # 5 minutes
  42. "15 min": 900, # 15 minutes
  43. "30 min": 1800, # 30 minutes
  44. "1 hour": 3600, # 1 hour
  45. "2 hour": 7200, # 2 hours
  46. "3 hour": 10800, # 3 hours
  47. "4 hour": 14400, # 4 hours
  48. "5 hour": 18000, # 5 hours
  49. "6 hour": 21600, # 6 hours
  50. "12 hour": 43200 # 12 hours
  51. }
  52. # Signals
  53. statusChanged = Signal()
  54. progressChanged = Signal()
  55. connectionChanged = Signal()
  56. executionStarted = Signal(str, str) # patternName, patternPreview
  57. executionStopped = Signal()
  58. errorOccurred = Signal(str)
  59. serialPortsUpdated = Signal(list)
  60. serialConnectionChanged = Signal(bool)
  61. currentPortChanged = Signal(str)
  62. speedChanged = Signal(int)
  63. settingsLoaded = Signal()
  64. screenStateChanged = Signal(bool) # True = on, False = off
  65. screenTimeoutChanged = Signal(int) # New signal for timeout changes
  66. pauseBetweenPatternsChanged = Signal(int) # New signal for pause changes
  67. # Backend connection status signals
  68. backendConnectionChanged = Signal(bool) # True = backend reachable, False = unreachable
  69. reconnectStatusChanged = Signal(str) # Current reconnection status message
  70. # LED control signals
  71. ledStatusChanged = Signal()
  72. ledEffectsLoaded = Signal(list) # List of available effects
  73. ledPalettesLoaded = Signal(list) # List of available palettes
  74. def __init__(self):
  75. super().__init__()
  76. # Load base URL from environment variable, default to localhost
  77. self.base_url = os.environ.get("DUNE_WEAVER_URL", "http://localhost:8080")
  78. # Initialize all status properties first
  79. self._current_file = ""
  80. self._progress = 0
  81. self._is_running = False
  82. self._is_connected = False
  83. self._serial_ports = []
  84. self._serial_connected = False
  85. self._current_port = ""
  86. self._current_speed = 130
  87. self._auto_play_on_boot = False
  88. self._pause_between_patterns = 0 # Default: no pause (0 seconds)
  89. # Backend connection status
  90. self._backend_connected = False
  91. self._reconnect_status = "Connecting to backend..."
  92. # LED control state
  93. self._led_provider = "none" # "none", "wled", or "dw_leds"
  94. self._led_connected = False
  95. self._led_power_on = False
  96. self._led_brightness = 100
  97. self._led_effects = []
  98. self._led_palettes = []
  99. self._led_current_effect = 0
  100. self._led_current_palette = 0
  101. self._led_color = "#ffffff"
  102. # WebSocket for status with reconnection
  103. self.ws = QWebSocket()
  104. self.ws.connected.connect(self._on_ws_connected)
  105. self.ws.disconnected.connect(self._on_ws_disconnected)
  106. self.ws.errorOccurred.connect(self._on_ws_error)
  107. self.ws.textMessageReceived.connect(self._on_ws_message)
  108. # WebSocket reconnection management
  109. self._reconnect_timer = QTimer()
  110. self._reconnect_timer.timeout.connect(self._attempt_ws_reconnect)
  111. self._reconnect_timer.setSingleShot(True)
  112. self._reconnect_attempts = 0
  113. self._reconnect_delay = 1000 # Fixed 1 second delay between retries
  114. # Screen management
  115. self._screen_on = True
  116. self._screen_timeout = self.DEFAULT_SCREEN_TIMEOUT # Will be loaded from settings
  117. self._last_activity = time.time()
  118. self._touch_monitor_thread = None
  119. self._screen_transition_lock = threading.Lock() # Prevent rapid state changes
  120. self._last_screen_change = 0 # Track last state change time
  121. self._use_touch_script = False # Disable external touch-monitor script (too sensitive)
  122. self._screen_timer = QTimer()
  123. self._screen_timer.timeout.connect(self._check_screen_timeout)
  124. self._screen_timer.start(1000) # Check every second
  125. # Load local settings first
  126. self._load_local_settings()
  127. print(f"🖥️ Screen management initialized: timeout={self._screen_timeout}s, timer started")
  128. # HTTP session - initialize lazily
  129. self.session = None
  130. self._session_initialized = False
  131. # Use QTimer to defer session initialization until event loop is running
  132. QTimer.singleShot(100, self._delayed_init)
  133. # Start initial WebSocket connection (after all attributes are initialized)
  134. # Use QTimer to ensure it happens after constructor completes
  135. QTimer.singleShot(200, self._attempt_ws_reconnect)
  136. @Slot()
  137. def _delayed_init(self):
  138. """Initialize session after Qt event loop is running"""
  139. if not self._session_initialized:
  140. try:
  141. loop = asyncio.get_event_loop()
  142. if loop.is_running():
  143. asyncio.create_task(self._init_session())
  144. else:
  145. # If no loop is running, try again later
  146. QTimer.singleShot(500, self._delayed_init)
  147. except RuntimeError:
  148. # No event loop yet, try again
  149. QTimer.singleShot(500, self._delayed_init)
  150. async def _init_session(self):
  151. """Initialize aiohttp session"""
  152. if not self._session_initialized:
  153. # Create connector with SSL disabled for localhost
  154. connector = aiohttp.TCPConnector(ssl=False)
  155. self.session = aiohttp.ClientSession(connector=connector)
  156. self._session_initialized = True
  157. # Properties
  158. @Property(str, notify=statusChanged)
  159. def currentFile(self):
  160. return self._current_file
  161. @Property(float, notify=progressChanged)
  162. def progress(self):
  163. return self._progress
  164. @Property(bool, notify=statusChanged)
  165. def isRunning(self):
  166. return self._is_running
  167. @Property(bool, notify=connectionChanged)
  168. def isConnected(self):
  169. return self._is_connected
  170. @Property(list, notify=serialPortsUpdated)
  171. def serialPorts(self):
  172. return self._serial_ports
  173. @Property(bool, notify=serialConnectionChanged)
  174. def serialConnected(self):
  175. return self._serial_connected
  176. @Property(str, notify=currentPortChanged)
  177. def currentPort(self):
  178. return self._current_port
  179. @Property(int, notify=speedChanged)
  180. def currentSpeed(self):
  181. return self._current_speed
  182. @Property(bool, notify=settingsLoaded)
  183. def autoPlayOnBoot(self):
  184. return self._auto_play_on_boot
  185. @Property(bool, notify=backendConnectionChanged)
  186. def backendConnected(self):
  187. return self._backend_connected
  188. @Property(str, notify=reconnectStatusChanged)
  189. def reconnectStatus(self):
  190. return self._reconnect_status
  191. # WebSocket handlers
  192. @Slot()
  193. def _on_ws_connected(self):
  194. print("✅ WebSocket connected successfully")
  195. self._is_connected = True
  196. self._backend_connected = True
  197. self._reconnect_attempts = 0 # Reset reconnection counter
  198. self._reconnect_status = "Connected to backend"
  199. self.connectionChanged.emit()
  200. self.backendConnectionChanged.emit(True)
  201. self.reconnectStatusChanged.emit("Connected to backend")
  202. # Load initial settings when we connect
  203. self.loadControlSettings()
  204. # Also load LED config automatically
  205. self.loadLedConfig()
  206. @Slot()
  207. def _on_ws_disconnected(self):
  208. print("❌ WebSocket disconnected")
  209. self._is_connected = False
  210. self._backend_connected = False
  211. self._reconnect_status = "Backend connection lost..."
  212. self.connectionChanged.emit()
  213. self.backendConnectionChanged.emit(False)
  214. self.reconnectStatusChanged.emit("Backend connection lost...")
  215. # Start reconnection attempts
  216. self._schedule_reconnect()
  217. @Slot()
  218. def _on_ws_error(self, error):
  219. print(f"❌ WebSocket error: {error}")
  220. self._is_connected = False
  221. self._backend_connected = False
  222. self._reconnect_status = f"Backend error: {error}"
  223. self.connectionChanged.emit()
  224. self.backendConnectionChanged.emit(False)
  225. self.reconnectStatusChanged.emit(f"Backend error: {error}")
  226. # Start reconnection attempts
  227. self._schedule_reconnect()
  228. def _schedule_reconnect(self):
  229. """Schedule a reconnection attempt with fixed 1-second delay."""
  230. # Always retry - no maximum attempts for touch interface
  231. status_msg = f"Reconnecting in 1s... (attempt {self._reconnect_attempts + 1})"
  232. print(f"🔄 {status_msg}")
  233. self._reconnect_status = status_msg
  234. self.reconnectStatusChanged.emit(status_msg)
  235. self._reconnect_timer.start(self._reconnect_delay) # Always 1 second
  236. @Slot()
  237. def _attempt_ws_reconnect(self):
  238. """Attempt to reconnect WebSocket."""
  239. if self.ws.state() == QAbstractSocket.SocketState.ConnectedState:
  240. print("✅ WebSocket already connected")
  241. return
  242. self._reconnect_attempts += 1
  243. status_msg = f"Connecting to backend... (attempt {self._reconnect_attempts})"
  244. print(f"🔄 {status_msg}")
  245. self._reconnect_status = status_msg
  246. self.reconnectStatusChanged.emit(status_msg)
  247. # Close existing connection if any
  248. if self.ws.state() != QAbstractSocket.SocketState.UnconnectedState:
  249. self.ws.close()
  250. # Attempt new connection - derive WebSocket URL from base URL
  251. ws_url = self.base_url.replace("http://", "ws://").replace("https://", "wss://") + "/ws/status"
  252. self.ws.open(ws_url)
  253. @Slot()
  254. def retryConnection(self):
  255. """Manually retry connection (reset attempts and try again)."""
  256. print("🔄 Manual connection retry requested")
  257. self._reconnect_attempts = 0
  258. self._reconnect_timer.stop() # Stop any scheduled reconnect
  259. self._attempt_ws_reconnect()
  260. @Slot(str)
  261. def _on_ws_message(self, message):
  262. try:
  263. data = json.loads(message)
  264. if data.get("type") == "status_update":
  265. status = data.get("data", {})
  266. new_file = status.get("current_file", "")
  267. # Detect pattern change and emit executionStarted signal
  268. if new_file and new_file != self._current_file:
  269. print(f"🎯 Pattern changed from '{self._current_file}' to '{new_file}'")
  270. # Find preview for the new pattern
  271. preview_path = self._find_pattern_preview(new_file)
  272. print(f"🖼️ Preview path for new pattern: {preview_path}")
  273. # Emit signal so UI can update
  274. self.executionStarted.emit(new_file, preview_path)
  275. self._current_file = new_file
  276. self._is_running = status.get("is_running", False)
  277. # Handle serial connection status from WebSocket
  278. ws_connection_status = status.get("connection_status", False)
  279. if ws_connection_status != self._serial_connected:
  280. print(f"🔌 WebSocket serial connection status changed: {ws_connection_status}")
  281. self._serial_connected = ws_connection_status
  282. self.serialConnectionChanged.emit(ws_connection_status)
  283. # If we're connected, we need to get the current port
  284. if ws_connection_status:
  285. # We'll need to fetch the current port via HTTP since WS doesn't include port info
  286. asyncio.create_task(self._get_current_port())
  287. else:
  288. self._current_port = ""
  289. self.currentPortChanged.emit("")
  290. # Handle speed updates from WebSocket
  291. ws_speed = status.get("speed", None)
  292. if ws_speed and ws_speed != self._current_speed:
  293. print(f"⚡ WebSocket speed changed: {ws_speed}")
  294. self._current_speed = ws_speed
  295. self.speedChanged.emit(ws_speed)
  296. if status.get("progress"):
  297. self._progress = status["progress"].get("percentage", 0)
  298. self.statusChanged.emit()
  299. self.progressChanged.emit()
  300. except json.JSONDecodeError:
  301. pass
  302. async def _get_current_port(self):
  303. """Fetch the current port when we detect a connection via WebSocket"""
  304. if not self.session:
  305. return
  306. try:
  307. async with self.session.get(f"{self.base_url}/serial_status") as resp:
  308. if resp.status == 200:
  309. data = await resp.json()
  310. current_port = data.get("port", "")
  311. if current_port:
  312. self._current_port = current_port
  313. self.currentPortChanged.emit(current_port)
  314. print(f"🔌 Updated current port from WebSocket trigger: {current_port}")
  315. except Exception as e:
  316. print(f"💥 Exception getting current port: {e}")
  317. # API Methods
  318. @Slot(str, str)
  319. def executePattern(self, fileName, preExecution="adaptive"):
  320. print(f"🎯 ExecutePattern called: fileName='{fileName}', preExecution='{preExecution}'")
  321. asyncio.create_task(self._execute_pattern(fileName, preExecution))
  322. async def _execute_pattern(self, fileName, preExecution):
  323. if not self.session:
  324. print("❌ Backend session not ready")
  325. self.errorOccurred.emit("Backend not ready, please try again")
  326. return
  327. try:
  328. request_data = {"file_name": fileName, "pre_execution": preExecution}
  329. print(f"🔄 Making HTTP POST to: {self.base_url}/run_theta_rho")
  330. print(f"📝 Request payload: {request_data}")
  331. async with self.session.post(
  332. f"{self.base_url}/run_theta_rho",
  333. json=request_data
  334. ) as resp:
  335. print(f"📡 Response status: {resp.status}")
  336. print(f"📋 Response headers: {dict(resp.headers)}")
  337. response_text = await resp.text()
  338. print(f"📄 Response body: {response_text}")
  339. if resp.status == 200:
  340. print("✅ Pattern execution request successful")
  341. # Find preview image for the pattern
  342. preview_path = self._find_pattern_preview(fileName)
  343. print(f"🖼️ Pattern preview path: {preview_path}")
  344. print(f"📡 About to emit executionStarted signal with: fileName='{fileName}', preview='{preview_path}'")
  345. try:
  346. self.executionStarted.emit(fileName, preview_path)
  347. print("✅ ExecutionStarted signal emitted successfully")
  348. except Exception as e:
  349. print(f"❌ Error emitting executionStarted signal: {e}")
  350. else:
  351. print(f"❌ Pattern execution failed with status {resp.status}")
  352. self.errorOccurred.emit(f"Failed to execute: {resp.status} - {response_text}")
  353. except Exception as e:
  354. print(f"💥 Exception in _execute_pattern: {e}")
  355. self.errorOccurred.emit(str(e))
  356. def _find_pattern_preview(self, fileName):
  357. """Find the preview image for a pattern"""
  358. try:
  359. # Extract just the filename from the path (remove any directory prefixes)
  360. clean_filename = fileName.split('/')[-1] # Get last part of path
  361. print(f"🔍 Original fileName: {fileName}, clean filename: {clean_filename}")
  362. # Check multiple possible locations for patterns directory
  363. # Use relative paths that work across different environments
  364. possible_dirs = [
  365. Path("../patterns"), # One level up (for when running from touch subdirectory)
  366. Path("patterns"), # Same level (for when running from main directory)
  367. Path(__file__).parent.parent / "patterns" # Dynamic path relative to backend.py
  368. ]
  369. for patterns_dir in possible_dirs:
  370. cache_dir = patterns_dir / "cached_images"
  371. if cache_dir.exists():
  372. print(f"🔍 Searching for preview in cache directory: {cache_dir}")
  373. # Extensions to try - PNG first for better kiosk compatibility
  374. extensions = [".png", ".webp", ".jpg", ".jpeg"]
  375. # Filenames to try - with and without .thr suffix
  376. base_name = clean_filename.replace(".thr", "")
  377. filenames_to_try = [clean_filename, base_name]
  378. # Try direct path in cache_dir first (fastest)
  379. for filename in filenames_to_try:
  380. for ext in extensions:
  381. preview_file = cache_dir / (filename + ext)
  382. if preview_file.exists():
  383. print(f"✅ Found preview (direct): {preview_file}")
  384. return str(preview_file.absolute())
  385. # If not found directly, search recursively through subdirectories
  386. print(f"🔍 Searching recursively in {cache_dir}...")
  387. for filename in filenames_to_try:
  388. for ext in extensions:
  389. target_name = filename + ext
  390. # Use rglob to search recursively
  391. matches = list(cache_dir.rglob(target_name))
  392. if matches:
  393. # Return the first match found
  394. preview_file = matches[0]
  395. print(f"✅ Found preview (recursive): {preview_file}")
  396. return str(preview_file.absolute())
  397. print("❌ No preview image found")
  398. return ""
  399. except Exception as e:
  400. print(f"💥 Exception finding preview: {e}")
  401. return ""
  402. @Slot()
  403. def stopExecution(self):
  404. asyncio.create_task(self._stop_execution())
  405. async def _stop_execution(self):
  406. if not self.session:
  407. self.errorOccurred.emit("Backend not ready")
  408. return
  409. try:
  410. print("🛑 Calling stop_execution endpoint...")
  411. # Add timeout to prevent hanging
  412. timeout = aiohttp.ClientTimeout(total=10) # 10 second timeout
  413. async with self.session.post(f"{self.base_url}/stop_execution", timeout=timeout) as resp:
  414. print(f"🛑 Stop execution response status: {resp.status}")
  415. if resp.status == 200:
  416. response_data = await resp.json()
  417. print(f"🛑 Stop execution response: {response_data}")
  418. self.executionStopped.emit()
  419. else:
  420. print(f"❌ Stop execution failed with status: {resp.status}")
  421. response_text = await resp.text()
  422. self.errorOccurred.emit(f"Stop failed: {resp.status} - {response_text}")
  423. except asyncio.TimeoutError:
  424. print("⏰ Stop execution request timed out")
  425. self.errorOccurred.emit("Stop execution request timed out")
  426. except Exception as e:
  427. print(f"💥 Exception in _stop_execution: {e}")
  428. self.errorOccurred.emit(str(e))
  429. @Slot()
  430. def pauseExecution(self):
  431. print("⏸️ Pausing execution...")
  432. asyncio.create_task(self._api_call("/pause_execution"))
  433. @Slot()
  434. def resumeExecution(self):
  435. print("▶️ Resuming execution...")
  436. asyncio.create_task(self._api_call("/resume_execution"))
  437. @Slot()
  438. def skipPattern(self):
  439. print("⏭️ Skipping pattern...")
  440. asyncio.create_task(self._api_call("/skip_pattern"))
  441. @Slot(str, float, str, str, bool)
  442. def executePlaylist(self, playlistName, pauseTime=0.0, clearPattern="adaptive", runMode="single", shuffle=False):
  443. print(f"🎵 ExecutePlaylist called: playlist='{playlistName}', pauseTime={pauseTime}, clearPattern='{clearPattern}', runMode='{runMode}', shuffle={shuffle}")
  444. asyncio.create_task(self._execute_playlist(playlistName, pauseTime, clearPattern, runMode, shuffle))
  445. async def _execute_playlist(self, playlistName, pauseTime, clearPattern, runMode, shuffle):
  446. if not self.session:
  447. print("❌ Backend session not ready")
  448. self.errorOccurred.emit("Backend not ready, please try again")
  449. return
  450. try:
  451. request_data = {
  452. "playlist_name": playlistName,
  453. "pause_time": pauseTime,
  454. "clear_pattern": clearPattern,
  455. "run_mode": runMode,
  456. "shuffle": shuffle
  457. }
  458. print(f"🔄 Making HTTP POST to: {self.base_url}/run_playlist")
  459. print(f"📝 Request payload: {request_data}")
  460. async with self.session.post(
  461. f"{self.base_url}/run_playlist",
  462. json=request_data
  463. ) as resp:
  464. print(f"📡 Response status: {resp.status}")
  465. response_text = await resp.text()
  466. print(f"📄 Response body: {response_text}")
  467. if resp.status == 200:
  468. print(f"✅ Playlist execution request successful: {playlistName}")
  469. # The playlist will start executing patterns automatically
  470. # Status updates will come through WebSocket
  471. else:
  472. print(f"❌ Playlist execution failed with status {resp.status}")
  473. self.errorOccurred.emit(f"Failed to execute playlist: {resp.status} - {response_text}")
  474. except Exception as e:
  475. print(f"💥 Exception in _execute_playlist: {e}")
  476. self.errorOccurred.emit(str(e))
  477. async def _api_call(self, endpoint):
  478. if not self.session:
  479. self.errorOccurred.emit("Backend not ready")
  480. return
  481. try:
  482. print(f"📡 Calling API endpoint: {endpoint}")
  483. # Add timeout to prevent hanging
  484. timeout = aiohttp.ClientTimeout(total=10) # 10 second timeout
  485. async with self.session.post(f"{self.base_url}{endpoint}", timeout=timeout) as resp:
  486. print(f"📡 API response status for {endpoint}: {resp.status}")
  487. if resp.status == 200:
  488. response_data = await resp.json()
  489. print(f"📡 API response for {endpoint}: {response_data}")
  490. else:
  491. print(f"❌ API call {endpoint} failed with status: {resp.status}")
  492. response_text = await resp.text()
  493. self.errorOccurred.emit(f"API call failed: {endpoint} - {resp.status} - {response_text}")
  494. except asyncio.TimeoutError:
  495. print(f"⏰ API call {endpoint} timed out")
  496. self.errorOccurred.emit(f"API call {endpoint} timed out")
  497. except Exception as e:
  498. print(f"💥 Exception in API call {endpoint}: {e}")
  499. self.errorOccurred.emit(str(e))
  500. # Serial Port Management
  501. @Slot()
  502. def refreshSerialPorts(self):
  503. print("🔌 Refreshing serial ports...")
  504. asyncio.create_task(self._refresh_serial_ports())
  505. async def _refresh_serial_ports(self):
  506. if not self.session:
  507. self.errorOccurred.emit("Backend not ready")
  508. return
  509. try:
  510. async with self.session.get(f"{self.base_url}/list_serial_ports") as resp:
  511. if resp.status == 200:
  512. # The endpoint returns a list directly, not a dictionary
  513. ports = await resp.json()
  514. self._serial_ports = ports if isinstance(ports, list) else []
  515. print(f"📡 Found serial ports: {self._serial_ports}")
  516. self.serialPortsUpdated.emit(self._serial_ports)
  517. else:
  518. print(f"❌ Failed to get serial ports: {resp.status}")
  519. except Exception as e:
  520. print(f"💥 Exception refreshing serial ports: {e}")
  521. self.errorOccurred.emit(str(e))
  522. @Slot(str)
  523. def connectSerial(self, port):
  524. print(f"🔗 Connecting to serial port: {port}")
  525. asyncio.create_task(self._connect_serial(port))
  526. async def _connect_serial(self, port):
  527. if not self.session:
  528. self.errorOccurred.emit("Backend not ready")
  529. return
  530. try:
  531. async with self.session.post(f"{self.base_url}/connect", json={"port": port}) as resp:
  532. if resp.status == 200:
  533. print(f"✅ Connected to {port}")
  534. self._serial_connected = True
  535. self._current_port = port
  536. self.serialConnectionChanged.emit(True)
  537. self.currentPortChanged.emit(port)
  538. else:
  539. response_text = await resp.text()
  540. print(f"❌ Failed to connect to {port}: {resp.status} - {response_text}")
  541. self.errorOccurred.emit(f"Failed to connect: {response_text}")
  542. except Exception as e:
  543. print(f"💥 Exception connecting to serial: {e}")
  544. self.errorOccurred.emit(str(e))
  545. @Slot()
  546. def disconnectSerial(self):
  547. print("🔌 Disconnecting serial...")
  548. asyncio.create_task(self._disconnect_serial())
  549. async def _disconnect_serial(self):
  550. if not self.session:
  551. self.errorOccurred.emit("Backend not ready")
  552. return
  553. try:
  554. async with self.session.post(f"{self.base_url}/disconnect") as resp:
  555. if resp.status == 200:
  556. print("✅ Disconnected from serial")
  557. self._serial_connected = False
  558. self._current_port = ""
  559. self.serialConnectionChanged.emit(False)
  560. self.currentPortChanged.emit("")
  561. else:
  562. response_text = await resp.text()
  563. print(f"❌ Failed to disconnect: {resp.status} - {response_text}")
  564. except Exception as e:
  565. print(f"💥 Exception disconnecting serial: {e}")
  566. self.errorOccurred.emit(str(e))
  567. # Hardware Movement Controls
  568. @Slot()
  569. def sendHome(self):
  570. print("🏠 Sending home command...")
  571. asyncio.create_task(self._api_call("/send_home"))
  572. @Slot()
  573. def moveToCenter(self):
  574. print("🎯 Moving to center...")
  575. asyncio.create_task(self._api_call("/move_to_center"))
  576. @Slot()
  577. def moveToPerimeter(self):
  578. print("⭕ Moving to perimeter...")
  579. asyncio.create_task(self._api_call("/move_to_perimeter"))
  580. # Speed Control
  581. @Slot(int)
  582. def setSpeed(self, speed):
  583. print(f"⚡ Setting speed to: {speed}")
  584. asyncio.create_task(self._set_speed(speed))
  585. async def _set_speed(self, speed):
  586. if not self.session:
  587. self.errorOccurred.emit("Backend not ready")
  588. return
  589. try:
  590. async with self.session.post(f"{self.base_url}/set_speed", json={"speed": speed}) as resp:
  591. if resp.status == 200:
  592. print(f"✅ Speed set to {speed}")
  593. self._current_speed = speed
  594. self.speedChanged.emit(speed)
  595. else:
  596. response_text = await resp.text()
  597. print(f"❌ Failed to set speed: {resp.status} - {response_text}")
  598. except Exception as e:
  599. print(f"💥 Exception setting speed: {e}")
  600. self.errorOccurred.emit(str(e))
  601. # Auto Play on Boot Setting
  602. @Slot(bool)
  603. def setAutoPlayOnBoot(self, enabled):
  604. print(f"🚀 Setting auto play on boot: {enabled}")
  605. asyncio.create_task(self._set_auto_play_on_boot(enabled))
  606. async def _set_auto_play_on_boot(self, enabled):
  607. if not self.session:
  608. self.errorOccurred.emit("Backend not ready")
  609. return
  610. try:
  611. # Use the kiosk mode API endpoint for auto-play on boot
  612. async with self.session.post(f"{self.base_url}/api/kiosk-mode", json={"enabled": enabled}) as resp:
  613. if resp.status == 200:
  614. print(f"✅ Auto play on boot set to {enabled}")
  615. self._auto_play_on_boot = enabled
  616. else:
  617. response_text = await resp.text()
  618. print(f"❌ Failed to set auto play: {resp.status} - {response_text}")
  619. except Exception as e:
  620. print(f"💥 Exception setting auto play: {e}")
  621. self.errorOccurred.emit(str(e))
  622. # Note: Screen timeout is now managed locally in touch_settings.json
  623. # The main application doesn't have a kiosk-mode endpoint, so we manage this locally
  624. # Load Settings
  625. def _load_local_settings(self):
  626. """Load settings from local JSON file"""
  627. try:
  628. if os.path.exists(self.SETTINGS_FILE):
  629. with open(self.SETTINGS_FILE, 'r') as f:
  630. settings = json.load(f)
  631. screen_timeout = settings.get('screen_timeout', self.DEFAULT_SCREEN_TIMEOUT)
  632. if isinstance(screen_timeout, (int, float)) and screen_timeout >= 0:
  633. self._screen_timeout = int(screen_timeout)
  634. if screen_timeout == 0:
  635. print(f"🖥️ Loaded screen timeout from local settings: Never (0s)")
  636. else:
  637. print(f"🖥️ Loaded screen timeout from local settings: {self._screen_timeout}s")
  638. else:
  639. print(f"⚠️ Invalid screen timeout in settings, using default: {self.DEFAULT_SCREEN_TIMEOUT}s")
  640. else:
  641. print(f"📄 No local settings file found, creating with defaults")
  642. self._save_local_settings()
  643. except Exception as e:
  644. print(f"❌ Error loading local settings: {e}, using defaults")
  645. self._screen_timeout = self.DEFAULT_SCREEN_TIMEOUT
  646. def _save_local_settings(self):
  647. """Save settings to local JSON file"""
  648. try:
  649. settings = {
  650. 'screen_timeout': self._screen_timeout,
  651. 'version': '1.0'
  652. }
  653. with open(self.SETTINGS_FILE, 'w') as f:
  654. json.dump(settings, f, indent=2)
  655. print(f"💾 Saved local settings: screen_timeout={self._screen_timeout}s")
  656. except Exception as e:
  657. print(f"❌ Error saving local settings: {e}")
  658. @Slot()
  659. def loadControlSettings(self):
  660. print("📋 Loading control settings...")
  661. asyncio.create_task(self._load_settings())
  662. async def _load_settings(self):
  663. if not self.session:
  664. print("⚠️ Session not ready for loading settings")
  665. return
  666. try:
  667. # Load auto play setting from the working endpoint
  668. timeout = aiohttp.ClientTimeout(total=5) # 5 second timeout
  669. async with self.session.get(f"{self.base_url}/api/auto_play-mode", timeout=timeout) as resp:
  670. if resp.status == 200:
  671. data = await resp.json()
  672. self._auto_play_on_boot = data.get("enabled", False)
  673. print(f"🚀 Loaded auto play setting: {self._auto_play_on_boot}")
  674. # Note: Screen timeout is managed locally, not from server
  675. # Serial status will be handled by WebSocket updates automatically
  676. # But we still load the initial port info if connected
  677. async with self.session.get(f"{self.base_url}/serial_status", timeout=timeout) as resp:
  678. if resp.status == 200:
  679. data = await resp.json()
  680. initial_connected = data.get("connected", False)
  681. current_port = data.get("port", "")
  682. print(f"🔌 Initial serial status: connected={initial_connected}, port={current_port}")
  683. # Only update if WebSocket hasn't already set this
  684. if initial_connected and current_port and not self._current_port:
  685. self._current_port = current_port
  686. self.currentPortChanged.emit(current_port)
  687. # Set initial connection status (WebSocket will take over from here)
  688. if self._serial_connected != initial_connected:
  689. self._serial_connected = initial_connected
  690. self.serialConnectionChanged.emit(initial_connected)
  691. print("✅ Settings loaded - WebSocket will handle real-time updates")
  692. self.settingsLoaded.emit()
  693. except aiohttp.ClientConnectorError as e:
  694. print(f"⚠️ Cannot connect to backend at {self.base_url}: {e}")
  695. # Don't emit error - this is expected when backend is down
  696. # WebSocket will handle reconnection
  697. except asyncio.TimeoutError:
  698. print(f"⏰ Timeout loading settings from {self.base_url}")
  699. # Don't emit error - expected when backend is slow/down
  700. except Exception as e:
  701. print(f"💥 Unexpected error loading settings: {e}")
  702. # Only emit error for unexpected issues
  703. if "ssl" not in str(e).lower():
  704. self.errorOccurred.emit(str(e))
  705. # Screen Management Properties
  706. @Property(bool, notify=screenStateChanged)
  707. def screenOn(self):
  708. return self._screen_on
  709. @Property(int, notify=screenTimeoutChanged)
  710. def screenTimeout(self):
  711. return self._screen_timeout
  712. @screenTimeout.setter
  713. def setScreenTimeout(self, timeout):
  714. if self._screen_timeout != timeout:
  715. old_timeout = self._screen_timeout
  716. self._screen_timeout = timeout
  717. print(f"🖥️ Screen timeout changed from {old_timeout}s to {timeout}s")
  718. # Save to local settings
  719. self._save_local_settings()
  720. # Emit change signal for QML
  721. self.screenTimeoutChanged.emit(timeout)
  722. @Slot(result='QStringList')
  723. def getScreenTimeoutOptions(self):
  724. """Get list of screen timeout options for QML"""
  725. return list(self.TIMEOUT_OPTIONS.keys())
  726. @Slot(result=str)
  727. def getCurrentScreenTimeoutOption(self):
  728. """Get current screen timeout as option string"""
  729. current_timeout = self._screen_timeout
  730. for option, value in self.TIMEOUT_OPTIONS.items():
  731. if value == current_timeout:
  732. return option
  733. # If custom value, return closest match or custom description
  734. if current_timeout == 0:
  735. return "Never"
  736. elif current_timeout < 60:
  737. return f"{current_timeout} seconds"
  738. elif current_timeout < 3600:
  739. minutes = current_timeout // 60
  740. return f"{minutes} minute{'s' if minutes != 1 else ''}"
  741. else:
  742. hours = current_timeout // 3600
  743. return f"{hours} hour{'s' if hours != 1 else ''}"
  744. @Slot(str)
  745. def setScreenTimeoutByOption(self, option):
  746. """Set screen timeout by option string"""
  747. if option in self.TIMEOUT_OPTIONS:
  748. timeout_value = self.TIMEOUT_OPTIONS[option]
  749. # Don't call the setter method, just assign to trigger the property setter
  750. if self._screen_timeout != timeout_value:
  751. old_timeout = self._screen_timeout
  752. self._screen_timeout = timeout_value
  753. print(f"🖥️ Screen timeout changed from {old_timeout}s to {timeout_value}s ({option})")
  754. # Save to local settings
  755. self._save_local_settings()
  756. # Emit change signal for QML
  757. self.screenTimeoutChanged.emit(timeout_value)
  758. else:
  759. print(f"⚠️ Unknown timeout option: {option}")
  760. @Slot(result='QStringList')
  761. def getSpeedOptions(self):
  762. """Get list of speed options for QML"""
  763. return list(self.SPEED_OPTIONS.keys())
  764. @Slot(result=str)
  765. def getCurrentSpeedOption(self):
  766. """Get current speed as option string"""
  767. current_speed = self._current_speed
  768. for option, value in self.SPEED_OPTIONS.items():
  769. if value == current_speed:
  770. return option
  771. # If custom value, return as string
  772. return str(current_speed)
  773. @Slot(str)
  774. def setSpeedByOption(self, option):
  775. """Set speed by option string"""
  776. if option in self.SPEED_OPTIONS:
  777. speed_value = self.SPEED_OPTIONS[option]
  778. # Don't call setter method, just assign directly
  779. if self._current_speed != speed_value:
  780. old_speed = self._current_speed
  781. self._current_speed = speed_value
  782. print(f"⚡ Speed changed from {old_speed} to {speed_value} ({option})")
  783. # Send to main application
  784. asyncio.create_task(self._set_speed_async(speed_value))
  785. # Emit change signal for QML
  786. self.speedChanged.emit(speed_value)
  787. else:
  788. print(f"⚠️ Unknown speed option: {option}")
  789. async def _set_speed_async(self, speed):
  790. """Send speed to main application asynchronously"""
  791. if not self.session:
  792. return
  793. try:
  794. async with self.session.post(f"{self.base_url}/set_speed", json={"speed": speed}) as resp:
  795. if resp.status == 200:
  796. print(f"✅ Speed set successfully: {speed}")
  797. else:
  798. print(f"❌ Failed to set speed: {resp.status}")
  799. except Exception as e:
  800. print(f"💥 Exception setting speed: {e}")
  801. # Pause Between Patterns Methods
  802. @Slot(result='QStringList')
  803. def getPauseOptions(self):
  804. """Get list of pause between patterns options for QML"""
  805. return list(self.PAUSE_OPTIONS.keys())
  806. @Slot(result=str)
  807. def getCurrentPauseOption(self):
  808. """Get current pause between patterns as option string"""
  809. current_pause = self._pause_between_patterns
  810. for option, value in self.PAUSE_OPTIONS.items():
  811. if value == current_pause:
  812. return option
  813. # If custom value, return descriptive string
  814. if current_pause == 0:
  815. return "0s"
  816. elif current_pause < 60:
  817. return f"{current_pause}s"
  818. elif current_pause < 3600:
  819. minutes = current_pause // 60
  820. return f"{minutes} min"
  821. else:
  822. hours = current_pause // 3600
  823. return f"{hours} hour"
  824. @Slot(str)
  825. def setPauseByOption(self, option):
  826. """Set pause between patterns by option string"""
  827. if option in self.PAUSE_OPTIONS:
  828. pause_value = self.PAUSE_OPTIONS[option]
  829. if self._pause_between_patterns != pause_value:
  830. old_pause = self._pause_between_patterns
  831. self._pause_between_patterns = pause_value
  832. print(f"⏸️ Pause between patterns changed from {old_pause}s to {pause_value}s ({option})")
  833. # Emit change signal for QML
  834. self.pauseBetweenPatternsChanged.emit(pause_value)
  835. else:
  836. print(f"⚠️ Unknown pause option: {option}")
  837. # Property for pause between patterns
  838. @Property(int, notify=pauseBetweenPatternsChanged)
  839. def pauseBetweenPatterns(self):
  840. """Get current pause between patterns in seconds"""
  841. return self._pause_between_patterns
  842. # Screen Control Methods
  843. @Slot()
  844. def turnScreenOn(self):
  845. """Turn the screen on and reset activity timer"""
  846. if not self._screen_on:
  847. self._turn_screen_on()
  848. self._reset_activity_timer()
  849. @Slot()
  850. def turnScreenOff(self):
  851. """Turn the screen off"""
  852. self._turn_screen_off()
  853. # Start touch monitoring after manual screen off
  854. QTimer.singleShot(1000, self._start_touch_monitoring) # 1 second delay
  855. @Slot()
  856. def resetActivityTimer(self):
  857. """Reset the activity timer (call on user interaction)"""
  858. self._reset_activity_timer()
  859. if not self._screen_on:
  860. self._turn_screen_on()
  861. def _turn_screen_on(self):
  862. """Internal method to turn screen on"""
  863. with self._screen_transition_lock:
  864. # Debounce: Don't turn on if we just changed state
  865. time_since_change = time.time() - self._last_screen_change
  866. if time_since_change < 2.0: # 2 second debounce
  867. print(f"🖥️ Screen state change blocked (debounce: {time_since_change:.1f}s < 2s)")
  868. return
  869. if self._screen_on:
  870. print("🖥️ Screen already ON, skipping")
  871. return
  872. try:
  873. # Use the working screen-on script if available
  874. screen_on_script = Path('/usr/local/bin/screen-on')
  875. if screen_on_script.exists():
  876. result = subprocess.run(['sudo', '/usr/local/bin/screen-on'],
  877. capture_output=True, text=True, timeout=5)
  878. if result.returncode == 0:
  879. print("🖥️ Screen turned ON (screen-on script)")
  880. else:
  881. print(f"⚠️ screen-on script failed: {result.stderr}")
  882. else:
  883. # Fallback: Manual control matching the script
  884. # Unblank framebuffer and restore backlight
  885. max_brightness = 255
  886. try:
  887. result = subprocess.run(['cat', '/sys/class/backlight/*/max_brightness'],
  888. shell=True, capture_output=True, text=True, timeout=2)
  889. if result.returncode == 0 and result.stdout.strip():
  890. max_brightness = int(result.stdout.strip())
  891. except:
  892. pass
  893. subprocess.run(['sudo', 'sh', '-c',
  894. f'echo 0 > /sys/class/graphics/fb0/blank && echo {max_brightness} > /sys/class/backlight/*/brightness'],
  895. check=False, timeout=5)
  896. print(f"🖥️ Screen turned ON (manual, brightness: {max_brightness})")
  897. self._screen_on = True
  898. self._last_screen_change = time.time()
  899. self.screenStateChanged.emit(True)
  900. except Exception as e:
  901. print(f"❌ Failed to turn screen on: {e}")
  902. def _turn_screen_off(self):
  903. """Internal method to turn screen off"""
  904. print("🖥️ _turn_screen_off() called")
  905. with self._screen_transition_lock:
  906. # Debounce: Don't turn off if we just changed state
  907. time_since_change = time.time() - self._last_screen_change
  908. if time_since_change < 2.0: # 2 second debounce
  909. print(f"🖥️ Screen state change blocked (debounce: {time_since_change:.1f}s < 2s)")
  910. return
  911. if not self._screen_on:
  912. print("🖥️ Screen already OFF, skipping")
  913. return
  914. try:
  915. # Use the working screen-off script if available
  916. screen_off_script = Path('/usr/local/bin/screen-off')
  917. print(f"🖥️ Checking for screen-off script at: {screen_off_script}")
  918. print(f"🖥️ Script exists: {screen_off_script.exists()}")
  919. if screen_off_script.exists():
  920. print("🖥️ Executing screen-off script...")
  921. result = subprocess.run(['sudo', '/usr/local/bin/screen-off'],
  922. capture_output=True, text=True, timeout=10)
  923. print(f"🖥️ Script return code: {result.returncode}")
  924. if result.stdout:
  925. print(f"🖥️ Script stdout: {result.stdout}")
  926. if result.stderr:
  927. print(f"🖥️ Script stderr: {result.stderr}")
  928. if result.returncode == 0:
  929. print("✅ Screen turned OFF (screen-off script)")
  930. else:
  931. print(f"⚠️ screen-off script failed: return code {result.returncode}")
  932. else:
  933. print("🖥️ Using manual screen control...")
  934. # Fallback: Manual control matching the script
  935. # Blank framebuffer and turn off backlight
  936. subprocess.run(['sudo', 'sh', '-c',
  937. 'echo 0 > /sys/class/backlight/*/brightness && echo 1 > /sys/class/graphics/fb0/blank'],
  938. check=False, timeout=5)
  939. print("🖥️ Screen turned OFF (manual)")
  940. self._screen_on = False
  941. self._last_screen_change = time.time()
  942. self.screenStateChanged.emit(False)
  943. print("🖥️ Screen state set to OFF, signal emitted")
  944. except Exception as e:
  945. print(f"❌ Failed to turn screen off: {e}")
  946. import traceback
  947. traceback.print_exc()
  948. def _reset_activity_timer(self):
  949. """Reset the last activity timestamp"""
  950. old_time = self._last_activity
  951. self._last_activity = time.time()
  952. time_since_last = self._last_activity - old_time
  953. if time_since_last > 1: # Only log if it's been more than 1 second
  954. print(f"🖥️ Activity detected - timer reset (was idle for {time_since_last:.1f}s)")
  955. def _check_screen_timeout(self):
  956. """Check if screen should be turned off due to inactivity"""
  957. if self._screen_on and self._screen_timeout > 0: # Only check if timeout is enabled
  958. idle_time = time.time() - self._last_activity
  959. # Log every 10 seconds when getting close to timeout
  960. if idle_time > self._screen_timeout - 10 and idle_time % 10 < 1:
  961. print(f"🖥️ Screen idle for {idle_time:.0f}s (timeout at {self._screen_timeout}s)")
  962. if idle_time > self._screen_timeout:
  963. print(f"🖥️ Screen timeout reached! Idle for {idle_time:.0f}s (timeout: {self._screen_timeout}s)")
  964. self._turn_screen_off()
  965. # Add delay before starting touch monitoring to avoid catching residual events
  966. QTimer.singleShot(1000, self._start_touch_monitoring) # 1 second delay
  967. # If timeout is 0 (Never), screen stays on indefinitely
  968. def _start_touch_monitoring(self):
  969. """Start monitoring touch input for wake-up"""
  970. if self._touch_monitor_thread is None or not self._touch_monitor_thread.is_alive():
  971. self._touch_monitor_thread = threading.Thread(target=self._monitor_touch_input, daemon=True)
  972. self._touch_monitor_thread.start()
  973. def _monitor_touch_input(self):
  974. """Monitor touch input to wake up the screen"""
  975. print("👆 Starting touch monitoring for wake-up")
  976. # Add delay to let any residual touch events clear
  977. time.sleep(2)
  978. # Flush touch device to clear any buffered events
  979. try:
  980. # Find and flush touch device
  981. for i in range(5):
  982. device = f'/dev/input/event{i}'
  983. if Path(device).exists():
  984. try:
  985. # Read and discard any pending events
  986. with open(device, 'rb') as f:
  987. import fcntl
  988. import os
  989. fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
  990. while True:
  991. try:
  992. f.read(24) # Standard input_event size
  993. except:
  994. break
  995. print(f"👆 Flushed touch device: {device}")
  996. break
  997. except:
  998. continue
  999. except Exception as e:
  1000. print(f"👆 Could not flush touch device: {e}")
  1001. print("👆 Touch monitoring active")
  1002. try:
  1003. # Use external touch monitor script if available - but only if not too sensitive
  1004. touch_monitor_script = Path('/usr/local/bin/touch-monitor')
  1005. use_script = touch_monitor_script.exists() and hasattr(self, '_use_touch_script') and self._use_touch_script
  1006. if use_script:
  1007. print("👆 Using touch-monitor script")
  1008. # Add extra delay for script-based monitoring since it's more sensitive
  1009. time.sleep(3)
  1010. print("👆 Starting touch-monitor script after flush delay")
  1011. process = subprocess.Popen(['sudo', '/usr/local/bin/touch-monitor'],
  1012. stdout=subprocess.PIPE,
  1013. stderr=subprocess.PIPE)
  1014. # Wait for script to detect touch and wake screen
  1015. while not self._screen_on:
  1016. if process.poll() is not None: # Script exited (touch detected)
  1017. print("👆 Touch detected by monitor script")
  1018. self._turn_screen_on()
  1019. self._reset_activity_timer()
  1020. break
  1021. time.sleep(0.1)
  1022. if process.poll() is None:
  1023. process.terminate()
  1024. else:
  1025. # Fallback: Direct monitoring
  1026. # Find touch input device
  1027. touch_device = None
  1028. for i in range(5): # Check event0 through event4
  1029. device = f'/dev/input/event{i}'
  1030. if Path(device).exists():
  1031. # Check if it's a touch device
  1032. try:
  1033. info = subprocess.run(['udevadm', 'info', '--query=all', f'--name={device}'],
  1034. capture_output=True, text=True, timeout=2)
  1035. if 'touch' in info.stdout.lower() or 'ft5406' in info.stdout.lower():
  1036. touch_device = device
  1037. break
  1038. except:
  1039. pass
  1040. if not touch_device:
  1041. touch_device = '/dev/input/event0' # Default fallback
  1042. print(f"👆 Monitoring touch device: {touch_device}")
  1043. # Try evtest first (more responsive to single taps)
  1044. evtest_available = subprocess.run(['which', 'evtest'],
  1045. capture_output=True).returncode == 0
  1046. if evtest_available:
  1047. # Use evtest which is more sensitive to single touches
  1048. print("👆 Using evtest for touch detection")
  1049. process = subprocess.Popen(['sudo', 'evtest', touch_device],
  1050. stdout=subprocess.PIPE,
  1051. stderr=subprocess.DEVNULL,
  1052. text=True)
  1053. # Wait for any event line
  1054. while not self._screen_on:
  1055. try:
  1056. line = process.stdout.readline()
  1057. if line and 'Event:' in line:
  1058. print("👆 Touch detected via evtest - waking screen")
  1059. process.terminate()
  1060. self._turn_screen_on()
  1061. self._reset_activity_timer()
  1062. break
  1063. except:
  1064. pass
  1065. if process.poll() is not None:
  1066. break
  1067. time.sleep(0.01) # Small sleep to prevent CPU spinning
  1068. else:
  1069. # Fallback: Use cat with single byte read (more responsive)
  1070. print("👆 Using cat for touch detection")
  1071. process = subprocess.Popen(['sudo', 'cat', touch_device],
  1072. stdout=subprocess.PIPE,
  1073. stderr=subprocess.DEVNULL)
  1074. # Wait for any data (even 1 byte indicates touch)
  1075. while not self._screen_on:
  1076. try:
  1077. # Non-blocking check for data
  1078. import select
  1079. ready, _, _ = select.select([process.stdout], [], [], 0.1)
  1080. if ready:
  1081. data = process.stdout.read(1) # Read just 1 byte
  1082. if data:
  1083. print("👆 Touch detected - waking screen")
  1084. process.terminate()
  1085. self._turn_screen_on()
  1086. self._reset_activity_timer()
  1087. break
  1088. except:
  1089. pass
  1090. # Check if screen was turned on by other means
  1091. if self._screen_on:
  1092. process.terminate()
  1093. break
  1094. time.sleep(0.1)
  1095. except Exception as e:
  1096. print(f"❌ Error monitoring touch input: {e}")
  1097. print("👆 Touch monitoring stopped")
  1098. # ==================== LED Control Methods ====================
  1099. # LED Properties
  1100. @Property(str, notify=ledStatusChanged)
  1101. def ledProvider(self):
  1102. return self._led_provider
  1103. @Property(bool, notify=ledStatusChanged)
  1104. def ledConnected(self):
  1105. return self._led_connected
  1106. @Property(bool, notify=ledStatusChanged)
  1107. def ledPowerOn(self):
  1108. return self._led_power_on
  1109. @Property(int, notify=ledStatusChanged)
  1110. def ledBrightness(self):
  1111. return self._led_brightness
  1112. @Property(list, notify=ledEffectsLoaded)
  1113. def ledEffects(self):
  1114. return self._led_effects
  1115. @Property(list, notify=ledPalettesLoaded)
  1116. def ledPalettes(self):
  1117. return self._led_palettes
  1118. @Property(int, notify=ledStatusChanged)
  1119. def ledCurrentEffect(self):
  1120. return self._led_current_effect
  1121. @Property(int, notify=ledStatusChanged)
  1122. def ledCurrentPalette(self):
  1123. return self._led_current_palette
  1124. @Property(str, notify=ledStatusChanged)
  1125. def ledColor(self):
  1126. return self._led_color
  1127. @Slot()
  1128. def loadLedConfig(self):
  1129. """Load LED configuration from the server"""
  1130. print("💡 Loading LED configuration...")
  1131. asyncio.create_task(self._load_led_config())
  1132. async def _load_led_config(self):
  1133. if not self.session:
  1134. print("⚠️ Session not ready for LED config")
  1135. return
  1136. try:
  1137. timeout = aiohttp.ClientTimeout(total=5)
  1138. async with self.session.get(f"{self.base_url}/get_led_config", timeout=timeout) as resp:
  1139. if resp.status == 200:
  1140. data = await resp.json()
  1141. self._led_provider = data.get("provider", "none")
  1142. print(f"💡 LED provider: {self._led_provider}")
  1143. if self._led_provider == "dw_leds":
  1144. # Load DW LEDs status
  1145. await self._load_led_status()
  1146. await self._load_led_effects()
  1147. await self._load_led_palettes()
  1148. self.ledStatusChanged.emit()
  1149. else:
  1150. print(f"❌ Failed to get LED config: {resp.status}")
  1151. except Exception as e:
  1152. print(f"💥 Exception loading LED config: {e}")
  1153. async def _load_led_status(self):
  1154. """Load current LED status"""
  1155. if not self.session:
  1156. return
  1157. try:
  1158. timeout = aiohttp.ClientTimeout(total=5)
  1159. async with self.session.get(f"{self.base_url}/api/dw_leds/status", timeout=timeout) as resp:
  1160. if resp.status == 200:
  1161. data = await resp.json()
  1162. self._led_connected = data.get("connected", False)
  1163. self._led_power_on = data.get("power_on", False)
  1164. self._led_brightness = data.get("brightness", 100)
  1165. self._led_current_effect = data.get("current_effect", 0)
  1166. self._led_current_palette = data.get("current_palette", 0)
  1167. print(f"💡 LED status: connected={self._led_connected}, power={self._led_power_on}, brightness={self._led_brightness}")
  1168. self.ledStatusChanged.emit()
  1169. except Exception as e:
  1170. print(f"💥 Exception loading LED status: {e}")
  1171. async def _load_led_effects(self):
  1172. """Load available LED effects"""
  1173. if not self.session:
  1174. return
  1175. try:
  1176. timeout = aiohttp.ClientTimeout(total=5)
  1177. async with self.session.get(f"{self.base_url}/api/dw_leds/effects", timeout=timeout) as resp:
  1178. if resp.status == 200:
  1179. data = await resp.json()
  1180. # API returns effects as [[id, name], ...] arrays
  1181. raw_effects = data.get("effects", [])
  1182. # Convert to list of dicts for easier use in QML
  1183. self._led_effects = [{"id": e[0], "name": e[1]} for e in raw_effects if len(e) >= 2]
  1184. print(f"💡 Loaded {len(self._led_effects)} LED effects")
  1185. self.ledEffectsLoaded.emit(self._led_effects)
  1186. except Exception as e:
  1187. print(f"💥 Exception loading LED effects: {e}")
  1188. async def _load_led_palettes(self):
  1189. """Load available LED palettes"""
  1190. if not self.session:
  1191. return
  1192. try:
  1193. timeout = aiohttp.ClientTimeout(total=5)
  1194. async with self.session.get(f"{self.base_url}/api/dw_leds/palettes", timeout=timeout) as resp:
  1195. if resp.status == 200:
  1196. data = await resp.json()
  1197. # API returns palettes as [[id, name], ...] arrays
  1198. raw_palettes = data.get("palettes", [])
  1199. # Convert to list of dicts for easier use in QML
  1200. self._led_palettes = [{"id": p[0], "name": p[1]} for p in raw_palettes if len(p) >= 2]
  1201. print(f"💡 Loaded {len(self._led_palettes)} LED palettes")
  1202. self.ledPalettesLoaded.emit(self._led_palettes)
  1203. except Exception as e:
  1204. print(f"💥 Exception loading LED palettes: {e}")
  1205. @Slot()
  1206. def refreshLedStatus(self):
  1207. """Refresh LED status from server"""
  1208. print("💡 Refreshing LED status...")
  1209. asyncio.create_task(self._load_led_status())
  1210. @Slot()
  1211. def toggleLedPower(self):
  1212. """Toggle LED power on/off"""
  1213. print("💡 Toggling LED power...")
  1214. asyncio.create_task(self._toggle_led_power())
  1215. async def _toggle_led_power(self):
  1216. if not self.session:
  1217. self.errorOccurred.emit("Backend not ready")
  1218. return
  1219. try:
  1220. async with self.session.post(
  1221. f"{self.base_url}/api/dw_leds/power",
  1222. json={"state": 2} # Toggle
  1223. ) as resp:
  1224. if resp.status == 200:
  1225. data = await resp.json()
  1226. self._led_power_on = data.get("power_on", False)
  1227. self._led_connected = data.get("connected", False)
  1228. print(f"💡 LED power toggled: {self._led_power_on}")
  1229. self.ledStatusChanged.emit()
  1230. else:
  1231. self.errorOccurred.emit(f"Failed to toggle LED power: {resp.status}")
  1232. except Exception as e:
  1233. print(f"💥 Exception toggling LED power: {e}")
  1234. self.errorOccurred.emit(str(e))
  1235. @Slot(bool)
  1236. def setLedPower(self, on):
  1237. """Set LED power state (True=on, False=off)"""
  1238. print(f"💡 Setting LED power: {on}")
  1239. asyncio.create_task(self._set_led_power(on))
  1240. async def _set_led_power(self, on):
  1241. if not self.session:
  1242. self.errorOccurred.emit("Backend not ready")
  1243. return
  1244. try:
  1245. async with self.session.post(
  1246. f"{self.base_url}/api/dw_leds/power",
  1247. json={"state": 1 if on else 0}
  1248. ) as resp:
  1249. if resp.status == 200:
  1250. data = await resp.json()
  1251. self._led_power_on = data.get("power_on", False)
  1252. self._led_connected = data.get("connected", False)
  1253. print(f"💡 LED power set: {self._led_power_on}")
  1254. self.ledStatusChanged.emit()
  1255. else:
  1256. self.errorOccurred.emit(f"Failed to set LED power: {resp.status}")
  1257. except Exception as e:
  1258. print(f"💥 Exception setting LED power: {e}")
  1259. self.errorOccurred.emit(str(e))
  1260. @Slot(int)
  1261. def setLedBrightness(self, value):
  1262. """Set LED brightness (0-100)"""
  1263. print(f"💡 Setting LED brightness: {value}")
  1264. asyncio.create_task(self._set_led_brightness(value))
  1265. async def _set_led_brightness(self, value):
  1266. if not self.session:
  1267. self.errorOccurred.emit("Backend not ready")
  1268. return
  1269. try:
  1270. async with self.session.post(
  1271. f"{self.base_url}/api/dw_leds/brightness",
  1272. json={"value": value}
  1273. ) as resp:
  1274. if resp.status == 200:
  1275. self._led_brightness = value
  1276. print(f"💡 LED brightness set: {value}")
  1277. self.ledStatusChanged.emit()
  1278. else:
  1279. self.errorOccurred.emit(f"Failed to set brightness: {resp.status}")
  1280. except Exception as e:
  1281. print(f"💥 Exception setting LED brightness: {e}")
  1282. self.errorOccurred.emit(str(e))
  1283. @Slot(int, int, int)
  1284. def setLedColor(self, r, g, b):
  1285. """Set LED color using RGB values"""
  1286. print(f"💡 Setting LED color: RGB({r}, {g}, {b})")
  1287. asyncio.create_task(self._set_led_color(r, g, b))
  1288. async def _set_led_color(self, r, g, b):
  1289. if not self.session:
  1290. self.errorOccurred.emit("Backend not ready")
  1291. return
  1292. try:
  1293. async with self.session.post(
  1294. f"{self.base_url}/api/dw_leds/color",
  1295. json={"color": [r, g, b]}
  1296. ) as resp:
  1297. if resp.status == 200:
  1298. self._led_color = f"#{r:02x}{g:02x}{b:02x}"
  1299. print(f"💡 LED color set: {self._led_color}")
  1300. self.ledStatusChanged.emit()
  1301. else:
  1302. self.errorOccurred.emit(f"Failed to set color: {resp.status}")
  1303. except Exception as e:
  1304. print(f"💥 Exception setting LED color: {e}")
  1305. self.errorOccurred.emit(str(e))
  1306. @Slot(str)
  1307. def setLedColorHex(self, hexColor):
  1308. """Set LED color using hex string (e.g., '#ff0000')"""
  1309. # Parse hex color
  1310. hexColor = hexColor.lstrip('#')
  1311. if len(hexColor) == 6:
  1312. r = int(hexColor[0:2], 16)
  1313. g = int(hexColor[2:4], 16)
  1314. b = int(hexColor[4:6], 16)
  1315. self.setLedColor(r, g, b)
  1316. else:
  1317. print(f"⚠️ Invalid hex color: {hexColor}")
  1318. @Slot(int)
  1319. def setLedEffect(self, effectId):
  1320. """Set LED effect by ID"""
  1321. print(f"💡 Setting LED effect: {effectId}")
  1322. asyncio.create_task(self._set_led_effect(effectId))
  1323. async def _set_led_effect(self, effectId):
  1324. if not self.session:
  1325. self.errorOccurred.emit("Backend not ready")
  1326. return
  1327. try:
  1328. async with self.session.post(
  1329. f"{self.base_url}/api/dw_leds/effect",
  1330. json={"effect_id": effectId}
  1331. ) as resp:
  1332. if resp.status == 200:
  1333. self._led_current_effect = effectId
  1334. print(f"💡 LED effect set: {effectId}")
  1335. self.ledStatusChanged.emit()
  1336. else:
  1337. self.errorOccurred.emit(f"Failed to set effect: {resp.status}")
  1338. except Exception as e:
  1339. print(f"💥 Exception setting LED effect: {e}")
  1340. self.errorOccurred.emit(str(e))
  1341. @Slot(int)
  1342. def setLedPalette(self, paletteId):
  1343. """Set LED palette by ID"""
  1344. print(f"💡 Setting LED palette: {paletteId}")
  1345. asyncio.create_task(self._set_led_palette(paletteId))
  1346. async def _set_led_palette(self, paletteId):
  1347. if not self.session:
  1348. self.errorOccurred.emit("Backend not ready")
  1349. return
  1350. try:
  1351. async with self.session.post(
  1352. f"{self.base_url}/api/dw_leds/palette",
  1353. json={"palette_id": paletteId}
  1354. ) as resp:
  1355. if resp.status == 200:
  1356. self._led_current_palette = paletteId
  1357. print(f"💡 LED palette set: {paletteId}")
  1358. self.ledStatusChanged.emit()
  1359. else:
  1360. self.errorOccurred.emit(f"Failed to set palette: {resp.status}")
  1361. except Exception as e:
  1362. print(f"💥 Exception setting LED palette: {e}")
  1363. self.errorOccurred.emit(str(e))