backend.py 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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. "150": 150,
  34. "200": 200,
  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. }
  46. # Signals
  47. statusChanged = Signal()
  48. progressChanged = Signal()
  49. connectionChanged = Signal()
  50. executionStarted = Signal(str, str) # patternName, patternPreview
  51. executionStopped = Signal()
  52. errorOccurred = Signal(str)
  53. serialPortsUpdated = Signal(list)
  54. serialConnectionChanged = Signal(bool)
  55. currentPortChanged = Signal(str)
  56. speedChanged = Signal(int)
  57. settingsLoaded = Signal()
  58. screenStateChanged = Signal(bool) # True = on, False = off
  59. screenTimeoutChanged = Signal(int) # New signal for timeout changes
  60. pauseBetweenPatternsChanged = Signal(int) # New signal for pause changes
  61. # Backend connection status signals
  62. backendConnectionChanged = Signal(bool) # True = backend reachable, False = unreachable
  63. reconnectStatusChanged = Signal(str) # Current reconnection status message
  64. def __init__(self):
  65. super().__init__()
  66. self.base_url = "http://localhost:8080"
  67. # Initialize all status properties first
  68. self._current_file = ""
  69. self._progress = 0
  70. self._is_running = False
  71. self._is_connected = False
  72. self._serial_ports = []
  73. self._serial_connected = False
  74. self._current_port = ""
  75. self._current_speed = 130
  76. self._auto_play_on_boot = False
  77. self._pause_between_patterns = 0 # Default: no pause (0 seconds)
  78. # Backend connection status
  79. self._backend_connected = False
  80. self._reconnect_status = "Connecting to backend..."
  81. # WebSocket for status with reconnection
  82. self.ws = QWebSocket()
  83. self.ws.connected.connect(self._on_ws_connected)
  84. self.ws.disconnected.connect(self._on_ws_disconnected)
  85. self.ws.errorOccurred.connect(self._on_ws_error)
  86. self.ws.textMessageReceived.connect(self._on_ws_message)
  87. # WebSocket reconnection management
  88. self._reconnect_timer = QTimer()
  89. self._reconnect_timer.timeout.connect(self._attempt_ws_reconnect)
  90. self._reconnect_timer.setSingleShot(True)
  91. self._reconnect_attempts = 0
  92. self._reconnect_delay = 1000 # Fixed 1 second delay between retries
  93. # Screen management
  94. self._screen_on = True
  95. self._screen_timeout = self.DEFAULT_SCREEN_TIMEOUT # Will be loaded from settings
  96. self._last_activity = time.time()
  97. self._touch_monitor_thread = None
  98. self._screen_transition_lock = threading.Lock() # Prevent rapid state changes
  99. self._last_screen_change = 0 # Track last state change time
  100. self._use_touch_script = False # Disable external touch-monitor script (too sensitive)
  101. self._screen_timer = QTimer()
  102. self._screen_timer.timeout.connect(self._check_screen_timeout)
  103. self._screen_timer.start(1000) # Check every second
  104. # Load local settings first
  105. self._load_local_settings()
  106. print(f"🖥️ Screen management initialized: timeout={self._screen_timeout}s, timer started")
  107. # HTTP session - initialize lazily
  108. self.session = None
  109. self._session_initialized = False
  110. # Use QTimer to defer session initialization until event loop is running
  111. QTimer.singleShot(100, self._delayed_init)
  112. # Start initial WebSocket connection (after all attributes are initialized)
  113. # Use QTimer to ensure it happens after constructor completes
  114. QTimer.singleShot(200, self._attempt_ws_reconnect)
  115. @Slot()
  116. def _delayed_init(self):
  117. """Initialize session after Qt event loop is running"""
  118. if not self._session_initialized:
  119. try:
  120. loop = asyncio.get_event_loop()
  121. if loop.is_running():
  122. asyncio.create_task(self._init_session())
  123. else:
  124. # If no loop is running, try again later
  125. QTimer.singleShot(500, self._delayed_init)
  126. except RuntimeError:
  127. # No event loop yet, try again
  128. QTimer.singleShot(500, self._delayed_init)
  129. async def _init_session(self):
  130. """Initialize aiohttp session"""
  131. if not self._session_initialized:
  132. # Create connector with SSL disabled for localhost
  133. connector = aiohttp.TCPConnector(ssl=False)
  134. self.session = aiohttp.ClientSession(connector=connector)
  135. self._session_initialized = True
  136. # Properties
  137. @Property(str, notify=statusChanged)
  138. def currentFile(self):
  139. return self._current_file
  140. @Property(float, notify=progressChanged)
  141. def progress(self):
  142. return self._progress
  143. @Property(bool, notify=statusChanged)
  144. def isRunning(self):
  145. return self._is_running
  146. @Property(bool, notify=connectionChanged)
  147. def isConnected(self):
  148. return self._is_connected
  149. @Property(list, notify=serialPortsUpdated)
  150. def serialPorts(self):
  151. return self._serial_ports
  152. @Property(bool, notify=serialConnectionChanged)
  153. def serialConnected(self):
  154. return self._serial_connected
  155. @Property(str, notify=currentPortChanged)
  156. def currentPort(self):
  157. return self._current_port
  158. @Property(int, notify=speedChanged)
  159. def currentSpeed(self):
  160. return self._current_speed
  161. @Property(bool, notify=settingsLoaded)
  162. def autoPlayOnBoot(self):
  163. return self._auto_play_on_boot
  164. @Property(bool, notify=backendConnectionChanged)
  165. def backendConnected(self):
  166. return self._backend_connected
  167. @Property(str, notify=reconnectStatusChanged)
  168. def reconnectStatus(self):
  169. return self._reconnect_status
  170. # WebSocket handlers
  171. @Slot()
  172. def _on_ws_connected(self):
  173. print("✅ WebSocket connected successfully")
  174. self._is_connected = True
  175. self._backend_connected = True
  176. self._reconnect_attempts = 0 # Reset reconnection counter
  177. self._reconnect_status = "Connected to backend"
  178. self.connectionChanged.emit()
  179. self.backendConnectionChanged.emit(True)
  180. self.reconnectStatusChanged.emit("Connected to backend")
  181. # Load initial settings when we connect
  182. self.loadControlSettings()
  183. @Slot()
  184. def _on_ws_disconnected(self):
  185. print("❌ WebSocket disconnected")
  186. self._is_connected = False
  187. self._backend_connected = False
  188. self._reconnect_status = "Backend connection lost..."
  189. self.connectionChanged.emit()
  190. self.backendConnectionChanged.emit(False)
  191. self.reconnectStatusChanged.emit("Backend connection lost...")
  192. # Start reconnection attempts
  193. self._schedule_reconnect()
  194. @Slot()
  195. def _on_ws_error(self, error):
  196. print(f"❌ WebSocket error: {error}")
  197. self._is_connected = False
  198. self._backend_connected = False
  199. self._reconnect_status = f"Backend error: {error}"
  200. self.connectionChanged.emit()
  201. self.backendConnectionChanged.emit(False)
  202. self.reconnectStatusChanged.emit(f"Backend error: {error}")
  203. # Start reconnection attempts
  204. self._schedule_reconnect()
  205. def _schedule_reconnect(self):
  206. """Schedule a reconnection attempt with fixed 1-second delay."""
  207. # Always retry - no maximum attempts for touch interface
  208. status_msg = f"Reconnecting in 1s... (attempt {self._reconnect_attempts + 1})"
  209. print(f"🔄 {status_msg}")
  210. self._reconnect_status = status_msg
  211. self.reconnectStatusChanged.emit(status_msg)
  212. self._reconnect_timer.start(self._reconnect_delay) # Always 1 second
  213. @Slot()
  214. def _attempt_ws_reconnect(self):
  215. """Attempt to reconnect WebSocket."""
  216. if self.ws.state() == QAbstractSocket.SocketState.ConnectedState:
  217. print("✅ WebSocket already connected")
  218. return
  219. self._reconnect_attempts += 1
  220. status_msg = f"Connecting to backend... (attempt {self._reconnect_attempts})"
  221. print(f"🔄 {status_msg}")
  222. self._reconnect_status = status_msg
  223. self.reconnectStatusChanged.emit(status_msg)
  224. # Close existing connection if any
  225. if self.ws.state() != QAbstractSocket.SocketState.UnconnectedState:
  226. self.ws.close()
  227. # Attempt new connection
  228. self.ws.open("ws://localhost:8080/ws/status")
  229. @Slot()
  230. def retryConnection(self):
  231. """Manually retry connection (reset attempts and try again)."""
  232. print("🔄 Manual connection retry requested")
  233. self._reconnect_attempts = 0
  234. self._reconnect_timer.stop() # Stop any scheduled reconnect
  235. self._attempt_ws_reconnect()
  236. @Slot(str)
  237. def _on_ws_message(self, message):
  238. try:
  239. data = json.loads(message)
  240. if data.get("type") == "status_update":
  241. status = data.get("data", {})
  242. self._current_file = status.get("current_file", "")
  243. self._is_running = status.get("is_running", False)
  244. # Handle serial connection status from WebSocket
  245. ws_connection_status = status.get("connection_status", False)
  246. if ws_connection_status != self._serial_connected:
  247. print(f"🔌 WebSocket serial connection status changed: {ws_connection_status}")
  248. self._serial_connected = ws_connection_status
  249. self.serialConnectionChanged.emit(ws_connection_status)
  250. # If we're connected, we need to get the current port
  251. if ws_connection_status:
  252. # We'll need to fetch the current port via HTTP since WS doesn't include port info
  253. asyncio.create_task(self._get_current_port())
  254. else:
  255. self._current_port = ""
  256. self.currentPortChanged.emit("")
  257. # Handle speed updates from WebSocket
  258. ws_speed = status.get("speed", None)
  259. if ws_speed and ws_speed != self._current_speed:
  260. print(f"⚡ WebSocket speed changed: {ws_speed}")
  261. self._current_speed = ws_speed
  262. self.speedChanged.emit(ws_speed)
  263. if status.get("progress"):
  264. self._progress = status["progress"].get("percentage", 0)
  265. self.statusChanged.emit()
  266. self.progressChanged.emit()
  267. except json.JSONDecodeError:
  268. pass
  269. async def _get_current_port(self):
  270. """Fetch the current port when we detect a connection via WebSocket"""
  271. if not self.session:
  272. return
  273. try:
  274. async with self.session.get(f"{self.base_url}/serial_status") as resp:
  275. if resp.status == 200:
  276. data = await resp.json()
  277. current_port = data.get("port", "")
  278. if current_port:
  279. self._current_port = current_port
  280. self.currentPortChanged.emit(current_port)
  281. print(f"🔌 Updated current port from WebSocket trigger: {current_port}")
  282. except Exception as e:
  283. print(f"💥 Exception getting current port: {e}")
  284. # API Methods
  285. @Slot(str, str)
  286. def executePattern(self, fileName, preExecution="adaptive"):
  287. print(f"🎯 ExecutePattern called: fileName='{fileName}', preExecution='{preExecution}'")
  288. asyncio.create_task(self._execute_pattern(fileName, preExecution))
  289. async def _execute_pattern(self, fileName, preExecution):
  290. if not self.session:
  291. print("❌ Backend session not ready")
  292. self.errorOccurred.emit("Backend not ready, please try again")
  293. return
  294. try:
  295. request_data = {"file_name": fileName, "pre_execution": preExecution}
  296. print(f"🔄 Making HTTP POST to: {self.base_url}/run_theta_rho")
  297. print(f"📝 Request payload: {request_data}")
  298. async with self.session.post(
  299. f"{self.base_url}/run_theta_rho",
  300. json=request_data
  301. ) as resp:
  302. print(f"📡 Response status: {resp.status}")
  303. print(f"📋 Response headers: {dict(resp.headers)}")
  304. response_text = await resp.text()
  305. print(f"📄 Response body: {response_text}")
  306. if resp.status == 200:
  307. print("✅ Pattern execution request successful")
  308. # Find preview image for the pattern
  309. preview_path = self._find_pattern_preview(fileName)
  310. print(f"🖼️ Pattern preview path: {preview_path}")
  311. print(f"📡 About to emit executionStarted signal with: fileName='{fileName}', preview='{preview_path}'")
  312. try:
  313. self.executionStarted.emit(fileName, preview_path)
  314. print("✅ ExecutionStarted signal emitted successfully")
  315. except Exception as e:
  316. print(f"❌ Error emitting executionStarted signal: {e}")
  317. else:
  318. print(f"❌ Pattern execution failed with status {resp.status}")
  319. self.errorOccurred.emit(f"Failed to execute: {resp.status} - {response_text}")
  320. except Exception as e:
  321. print(f"💥 Exception in _execute_pattern: {e}")
  322. self.errorOccurred.emit(str(e))
  323. def _find_pattern_preview(self, fileName):
  324. """Find the preview image for a pattern"""
  325. try:
  326. # Extract just the filename from the path (remove any directory prefixes)
  327. clean_filename = fileName.split('/')[-1] # Get last part of path
  328. print(f"🔍 Original fileName: {fileName}, clean filename: {clean_filename}")
  329. # Check multiple possible locations for patterns directory
  330. # Use relative paths that work across different environments
  331. possible_dirs = [
  332. Path("../patterns"), # One level up (for when running from touch subdirectory)
  333. Path("patterns"), # Same level (for when running from main directory)
  334. Path(__file__).parent.parent / "patterns" # Dynamic path relative to backend.py
  335. ]
  336. for patterns_dir in possible_dirs:
  337. cache_dir = patterns_dir / "cached_images"
  338. if cache_dir.exists():
  339. print(f"🔍 Checking preview cache directory: {cache_dir}")
  340. # Use PNG format only for kiosk compatibility
  341. # First try with .thr suffix (e.g., pattern.thr.png)
  342. preview_file = cache_dir / (clean_filename + ".png")
  343. print(f"🔍 Looking for preview: {preview_file}")
  344. if preview_file.exists():
  345. print(f"✅ Found preview: {preview_file}")
  346. return str(preview_file.absolute())
  347. # Then try without .thr suffix (e.g., pattern.png)
  348. base_name = clean_filename.replace(".thr", "")
  349. preview_file = cache_dir / (base_name + ".png")
  350. print(f"🔍 Looking for preview (no .thr): {preview_file}")
  351. if preview_file.exists():
  352. print(f"✅ Found preview: {preview_file}")
  353. return str(preview_file.absolute())
  354. print("❌ No preview image found")
  355. return ""
  356. except Exception as e:
  357. print(f"💥 Exception finding preview: {e}")
  358. return ""
  359. @Slot()
  360. def stopExecution(self):
  361. asyncio.create_task(self._stop_execution())
  362. async def _stop_execution(self):
  363. if not self.session:
  364. self.errorOccurred.emit("Backend not ready")
  365. return
  366. try:
  367. print("🛑 Calling stop_execution endpoint...")
  368. # Add timeout to prevent hanging
  369. timeout = aiohttp.ClientTimeout(total=10) # 10 second timeout
  370. async with self.session.post(f"{self.base_url}/stop_execution", timeout=timeout) as resp:
  371. print(f"🛑 Stop execution response status: {resp.status}")
  372. if resp.status == 200:
  373. response_data = await resp.json()
  374. print(f"🛑 Stop execution response: {response_data}")
  375. self.executionStopped.emit()
  376. else:
  377. print(f"❌ Stop execution failed with status: {resp.status}")
  378. response_text = await resp.text()
  379. self.errorOccurred.emit(f"Stop failed: {resp.status} - {response_text}")
  380. except asyncio.TimeoutError:
  381. print("⏰ Stop execution request timed out")
  382. self.errorOccurred.emit("Stop execution request timed out")
  383. except Exception as e:
  384. print(f"💥 Exception in _stop_execution: {e}")
  385. self.errorOccurred.emit(str(e))
  386. @Slot()
  387. def pauseExecution(self):
  388. print("⏸️ Pausing execution...")
  389. asyncio.create_task(self._api_call("/pause_execution"))
  390. @Slot()
  391. def resumeExecution(self):
  392. print("▶️ Resuming execution...")
  393. asyncio.create_task(self._api_call("/resume_execution"))
  394. @Slot()
  395. def skipPattern(self):
  396. print("⏭️ Skipping pattern...")
  397. asyncio.create_task(self._api_call("/skip_pattern"))
  398. @Slot(str, float, str, str, bool)
  399. def executePlaylist(self, playlistName, pauseTime=0.0, clearPattern="adaptive", runMode="single", shuffle=False):
  400. print(f"🎵 ExecutePlaylist called: playlist='{playlistName}', pauseTime={pauseTime}, clearPattern='{clearPattern}', runMode='{runMode}', shuffle={shuffle}")
  401. asyncio.create_task(self._execute_playlist(playlistName, pauseTime, clearPattern, runMode, shuffle))
  402. async def _execute_playlist(self, playlistName, pauseTime, clearPattern, runMode, shuffle):
  403. if not self.session:
  404. print("❌ Backend session not ready")
  405. self.errorOccurred.emit("Backend not ready, please try again")
  406. return
  407. try:
  408. request_data = {
  409. "playlist_name": playlistName,
  410. "pause_time": pauseTime,
  411. "clear_pattern": clearPattern,
  412. "run_mode": runMode,
  413. "shuffle": shuffle
  414. }
  415. print(f"🔄 Making HTTP POST to: {self.base_url}/run_playlist")
  416. print(f"📝 Request payload: {request_data}")
  417. async with self.session.post(
  418. f"{self.base_url}/run_playlist",
  419. json=request_data
  420. ) as resp:
  421. print(f"📡 Response status: {resp.status}")
  422. response_text = await resp.text()
  423. print(f"📄 Response body: {response_text}")
  424. if resp.status == 200:
  425. print(f"✅ Playlist execution request successful: {playlistName}")
  426. # The playlist will start executing patterns automatically
  427. # Status updates will come through WebSocket
  428. else:
  429. print(f"❌ Playlist execution failed with status {resp.status}")
  430. self.errorOccurred.emit(f"Failed to execute playlist: {resp.status} - {response_text}")
  431. except Exception as e:
  432. print(f"💥 Exception in _execute_playlist: {e}")
  433. self.errorOccurred.emit(str(e))
  434. async def _api_call(self, endpoint):
  435. if not self.session:
  436. self.errorOccurred.emit("Backend not ready")
  437. return
  438. try:
  439. print(f"📡 Calling API endpoint: {endpoint}")
  440. # Add timeout to prevent hanging
  441. timeout = aiohttp.ClientTimeout(total=10) # 10 second timeout
  442. async with self.session.post(f"{self.base_url}{endpoint}", timeout=timeout) as resp:
  443. print(f"📡 API response status for {endpoint}: {resp.status}")
  444. if resp.status == 200:
  445. response_data = await resp.json()
  446. print(f"📡 API response for {endpoint}: {response_data}")
  447. else:
  448. print(f"❌ API call {endpoint} failed with status: {resp.status}")
  449. response_text = await resp.text()
  450. self.errorOccurred.emit(f"API call failed: {endpoint} - {resp.status} - {response_text}")
  451. except asyncio.TimeoutError:
  452. print(f"⏰ API call {endpoint} timed out")
  453. self.errorOccurred.emit(f"API call {endpoint} timed out")
  454. except Exception as e:
  455. print(f"💥 Exception in API call {endpoint}: {e}")
  456. self.errorOccurred.emit(str(e))
  457. # Serial Port Management
  458. @Slot()
  459. def refreshSerialPorts(self):
  460. print("🔌 Refreshing serial ports...")
  461. asyncio.create_task(self._refresh_serial_ports())
  462. async def _refresh_serial_ports(self):
  463. if not self.session:
  464. self.errorOccurred.emit("Backend not ready")
  465. return
  466. try:
  467. async with self.session.get(f"{self.base_url}/list_serial_ports") as resp:
  468. if resp.status == 200:
  469. # The endpoint returns a list directly, not a dictionary
  470. ports = await resp.json()
  471. self._serial_ports = ports if isinstance(ports, list) else []
  472. print(f"📡 Found serial ports: {self._serial_ports}")
  473. self.serialPortsUpdated.emit(self._serial_ports)
  474. else:
  475. print(f"❌ Failed to get serial ports: {resp.status}")
  476. except Exception as e:
  477. print(f"💥 Exception refreshing serial ports: {e}")
  478. self.errorOccurred.emit(str(e))
  479. @Slot(str)
  480. def connectSerial(self, port):
  481. print(f"🔗 Connecting to serial port: {port}")
  482. asyncio.create_task(self._connect_serial(port))
  483. async def _connect_serial(self, port):
  484. if not self.session:
  485. self.errorOccurred.emit("Backend not ready")
  486. return
  487. try:
  488. async with self.session.post(f"{self.base_url}/connect", json={"port": port}) as resp:
  489. if resp.status == 200:
  490. print(f"✅ Connected to {port}")
  491. self._serial_connected = True
  492. self._current_port = port
  493. self.serialConnectionChanged.emit(True)
  494. self.currentPortChanged.emit(port)
  495. else:
  496. response_text = await resp.text()
  497. print(f"❌ Failed to connect to {port}: {resp.status} - {response_text}")
  498. self.errorOccurred.emit(f"Failed to connect: {response_text}")
  499. except Exception as e:
  500. print(f"💥 Exception connecting to serial: {e}")
  501. self.errorOccurred.emit(str(e))
  502. @Slot()
  503. def disconnectSerial(self):
  504. print("🔌 Disconnecting serial...")
  505. asyncio.create_task(self._disconnect_serial())
  506. async def _disconnect_serial(self):
  507. if not self.session:
  508. self.errorOccurred.emit("Backend not ready")
  509. return
  510. try:
  511. async with self.session.post(f"{self.base_url}/disconnect") as resp:
  512. if resp.status == 200:
  513. print("✅ Disconnected from serial")
  514. self._serial_connected = False
  515. self._current_port = ""
  516. self.serialConnectionChanged.emit(False)
  517. self.currentPortChanged.emit("")
  518. else:
  519. response_text = await resp.text()
  520. print(f"❌ Failed to disconnect: {resp.status} - {response_text}")
  521. except Exception as e:
  522. print(f"💥 Exception disconnecting serial: {e}")
  523. self.errorOccurred.emit(str(e))
  524. # Hardware Movement Controls
  525. @Slot()
  526. def sendHome(self):
  527. print("🏠 Sending home command...")
  528. asyncio.create_task(self._api_call("/send_home"))
  529. @Slot()
  530. def moveToCenter(self):
  531. print("🎯 Moving to center...")
  532. asyncio.create_task(self._api_call("/move_to_center"))
  533. @Slot()
  534. def moveToPerimeter(self):
  535. print("⭕ Moving to perimeter...")
  536. asyncio.create_task(self._api_call("/move_to_perimeter"))
  537. # Speed Control
  538. @Slot(int)
  539. def setSpeed(self, speed):
  540. print(f"⚡ Setting speed to: {speed}")
  541. asyncio.create_task(self._set_speed(speed))
  542. async def _set_speed(self, speed):
  543. if not self.session:
  544. self.errorOccurred.emit("Backend not ready")
  545. return
  546. try:
  547. async with self.session.post(f"{self.base_url}/set_speed", json={"speed": speed}) as resp:
  548. if resp.status == 200:
  549. print(f"✅ Speed set to {speed}")
  550. self._current_speed = speed
  551. self.speedChanged.emit(speed)
  552. else:
  553. response_text = await resp.text()
  554. print(f"❌ Failed to set speed: {resp.status} - {response_text}")
  555. except Exception as e:
  556. print(f"💥 Exception setting speed: {e}")
  557. self.errorOccurred.emit(str(e))
  558. # Auto Play on Boot Setting
  559. @Slot(bool)
  560. def setAutoPlayOnBoot(self, enabled):
  561. print(f"🚀 Setting auto play on boot: {enabled}")
  562. asyncio.create_task(self._set_auto_play_on_boot(enabled))
  563. async def _set_auto_play_on_boot(self, enabled):
  564. if not self.session:
  565. self.errorOccurred.emit("Backend not ready")
  566. return
  567. try:
  568. # Use the kiosk mode API endpoint for auto-play on boot
  569. async with self.session.post(f"{self.base_url}/api/kiosk-mode", json={"enabled": enabled}) as resp:
  570. if resp.status == 200:
  571. print(f"✅ Auto play on boot set to {enabled}")
  572. self._auto_play_on_boot = enabled
  573. else:
  574. response_text = await resp.text()
  575. print(f"❌ Failed to set auto play: {resp.status} - {response_text}")
  576. except Exception as e:
  577. print(f"💥 Exception setting auto play: {e}")
  578. self.errorOccurred.emit(str(e))
  579. # Note: Screen timeout is now managed locally in touch_settings.json
  580. # The main application doesn't have a kiosk-mode endpoint, so we manage this locally
  581. # Load Settings
  582. def _load_local_settings(self):
  583. """Load settings from local JSON file"""
  584. try:
  585. if os.path.exists(self.SETTINGS_FILE):
  586. with open(self.SETTINGS_FILE, 'r') as f:
  587. settings = json.load(f)
  588. screen_timeout = settings.get('screen_timeout', self.DEFAULT_SCREEN_TIMEOUT)
  589. if isinstance(screen_timeout, (int, float)) and screen_timeout >= 0:
  590. self._screen_timeout = int(screen_timeout)
  591. if screen_timeout == 0:
  592. print(f"🖥️ Loaded screen timeout from local settings: Never (0s)")
  593. else:
  594. print(f"🖥️ Loaded screen timeout from local settings: {self._screen_timeout}s")
  595. else:
  596. print(f"⚠️ Invalid screen timeout in settings, using default: {self.DEFAULT_SCREEN_TIMEOUT}s")
  597. else:
  598. print(f"📄 No local settings file found, creating with defaults")
  599. self._save_local_settings()
  600. except Exception as e:
  601. print(f"❌ Error loading local settings: {e}, using defaults")
  602. self._screen_timeout = self.DEFAULT_SCREEN_TIMEOUT
  603. def _save_local_settings(self):
  604. """Save settings to local JSON file"""
  605. try:
  606. settings = {
  607. 'screen_timeout': self._screen_timeout,
  608. 'version': '1.0'
  609. }
  610. with open(self.SETTINGS_FILE, 'w') as f:
  611. json.dump(settings, f, indent=2)
  612. print(f"💾 Saved local settings: screen_timeout={self._screen_timeout}s")
  613. except Exception as e:
  614. print(f"❌ Error saving local settings: {e}")
  615. @Slot()
  616. def loadControlSettings(self):
  617. print("📋 Loading control settings...")
  618. asyncio.create_task(self._load_settings())
  619. async def _load_settings(self):
  620. if not self.session:
  621. print("⚠️ Session not ready for loading settings")
  622. return
  623. try:
  624. # Load auto play setting from the working endpoint
  625. timeout = aiohttp.ClientTimeout(total=5) # 5 second timeout
  626. async with self.session.get(f"{self.base_url}/api/auto_play-mode", timeout=timeout) as resp:
  627. if resp.status == 200:
  628. data = await resp.json()
  629. self._auto_play_on_boot = data.get("enabled", False)
  630. print(f"🚀 Loaded auto play setting: {self._auto_play_on_boot}")
  631. # Note: Screen timeout is managed locally, not from server
  632. # Serial status will be handled by WebSocket updates automatically
  633. # But we still load the initial port info if connected
  634. async with self.session.get(f"{self.base_url}/serial_status", timeout=timeout) as resp:
  635. if resp.status == 200:
  636. data = await resp.json()
  637. initial_connected = data.get("connected", False)
  638. current_port = data.get("port", "")
  639. print(f"🔌 Initial serial status: connected={initial_connected}, port={current_port}")
  640. # Only update if WebSocket hasn't already set this
  641. if initial_connected and current_port and not self._current_port:
  642. self._current_port = current_port
  643. self.currentPortChanged.emit(current_port)
  644. # Set initial connection status (WebSocket will take over from here)
  645. if self._serial_connected != initial_connected:
  646. self._serial_connected = initial_connected
  647. self.serialConnectionChanged.emit(initial_connected)
  648. print("✅ Settings loaded - WebSocket will handle real-time updates")
  649. self.settingsLoaded.emit()
  650. except aiohttp.ClientConnectorError as e:
  651. print(f"⚠️ Cannot connect to backend at {self.base_url}: {e}")
  652. # Don't emit error - this is expected when backend is down
  653. # WebSocket will handle reconnection
  654. except asyncio.TimeoutError:
  655. print(f"⏰ Timeout loading settings from {self.base_url}")
  656. # Don't emit error - expected when backend is slow/down
  657. except Exception as e:
  658. print(f"💥 Unexpected error loading settings: {e}")
  659. # Only emit error for unexpected issues
  660. if "ssl" not in str(e).lower():
  661. self.errorOccurred.emit(str(e))
  662. # Screen Management Properties
  663. @Property(bool, notify=screenStateChanged)
  664. def screenOn(self):
  665. return self._screen_on
  666. @Property(int, notify=screenTimeoutChanged)
  667. def screenTimeout(self):
  668. return self._screen_timeout
  669. @screenTimeout.setter
  670. def setScreenTimeout(self, timeout):
  671. if self._screen_timeout != timeout:
  672. old_timeout = self._screen_timeout
  673. self._screen_timeout = timeout
  674. print(f"🖥️ Screen timeout changed from {old_timeout}s to {timeout}s")
  675. # Save to local settings
  676. self._save_local_settings()
  677. # Emit change signal for QML
  678. self.screenTimeoutChanged.emit(timeout)
  679. @Slot(result='QStringList')
  680. def getScreenTimeoutOptions(self):
  681. """Get list of screen timeout options for QML"""
  682. return list(self.TIMEOUT_OPTIONS.keys())
  683. @Slot(result=str)
  684. def getCurrentScreenTimeoutOption(self):
  685. """Get current screen timeout as option string"""
  686. current_timeout = self._screen_timeout
  687. for option, value in self.TIMEOUT_OPTIONS.items():
  688. if value == current_timeout:
  689. return option
  690. # If custom value, return closest match or custom description
  691. if current_timeout == 0:
  692. return "Never"
  693. elif current_timeout < 60:
  694. return f"{current_timeout} seconds"
  695. elif current_timeout < 3600:
  696. minutes = current_timeout // 60
  697. return f"{minutes} minute{'s' if minutes != 1 else ''}"
  698. else:
  699. hours = current_timeout // 3600
  700. return f"{hours} hour{'s' if hours != 1 else ''}"
  701. @Slot(str)
  702. def setScreenTimeoutByOption(self, option):
  703. """Set screen timeout by option string"""
  704. if option in self.TIMEOUT_OPTIONS:
  705. timeout_value = self.TIMEOUT_OPTIONS[option]
  706. # Don't call the setter method, just assign to trigger the property setter
  707. if self._screen_timeout != timeout_value:
  708. old_timeout = self._screen_timeout
  709. self._screen_timeout = timeout_value
  710. print(f"🖥️ Screen timeout changed from {old_timeout}s to {timeout_value}s ({option})")
  711. # Save to local settings
  712. self._save_local_settings()
  713. # Emit change signal for QML
  714. self.screenTimeoutChanged.emit(timeout_value)
  715. else:
  716. print(f"⚠️ Unknown timeout option: {option}")
  717. @Slot(result='QStringList')
  718. def getSpeedOptions(self):
  719. """Get list of speed options for QML"""
  720. return list(self.SPEED_OPTIONS.keys())
  721. @Slot(result=str)
  722. def getCurrentSpeedOption(self):
  723. """Get current speed as option string"""
  724. current_speed = self._current_speed
  725. for option, value in self.SPEED_OPTIONS.items():
  726. if value == current_speed:
  727. return option
  728. # If custom value, return as string
  729. return str(current_speed)
  730. @Slot(str)
  731. def setSpeedByOption(self, option):
  732. """Set speed by option string"""
  733. if option in self.SPEED_OPTIONS:
  734. speed_value = self.SPEED_OPTIONS[option]
  735. # Don't call setter method, just assign directly
  736. if self._current_speed != speed_value:
  737. old_speed = self._current_speed
  738. self._current_speed = speed_value
  739. print(f"⚡ Speed changed from {old_speed} to {speed_value} ({option})")
  740. # Send to main application
  741. asyncio.create_task(self._set_speed_async(speed_value))
  742. # Emit change signal for QML
  743. self.speedChanged.emit(speed_value)
  744. else:
  745. print(f"⚠️ Unknown speed option: {option}")
  746. async def _set_speed_async(self, speed):
  747. """Send speed to main application asynchronously"""
  748. if not self.session:
  749. return
  750. try:
  751. async with self.session.post(f"{self.base_url}/set_speed", json={"speed": speed}) as resp:
  752. if resp.status == 200:
  753. print(f"✅ Speed set successfully: {speed}")
  754. else:
  755. print(f"❌ Failed to set speed: {resp.status}")
  756. except Exception as e:
  757. print(f"💥 Exception setting speed: {e}")
  758. # Pause Between Patterns Methods
  759. @Slot(result='QStringList')
  760. def getPauseOptions(self):
  761. """Get list of pause between patterns options for QML"""
  762. return list(self.PAUSE_OPTIONS.keys())
  763. @Slot(result=str)
  764. def getCurrentPauseOption(self):
  765. """Get current pause between patterns as option string"""
  766. current_pause = self._pause_between_patterns
  767. for option, value in self.PAUSE_OPTIONS.items():
  768. if value == current_pause:
  769. return option
  770. # If custom value, return descriptive string
  771. if current_pause == 0:
  772. return "0s"
  773. elif current_pause < 60:
  774. return f"{current_pause}s"
  775. elif current_pause < 3600:
  776. minutes = current_pause // 60
  777. return f"{minutes} min"
  778. else:
  779. hours = current_pause // 3600
  780. return f"{hours} hour"
  781. @Slot(str)
  782. def setPauseByOption(self, option):
  783. """Set pause between patterns by option string"""
  784. if option in self.PAUSE_OPTIONS:
  785. pause_value = self.PAUSE_OPTIONS[option]
  786. if self._pause_between_patterns != pause_value:
  787. old_pause = self._pause_between_patterns
  788. self._pause_between_patterns = pause_value
  789. print(f"⏸️ Pause between patterns changed from {old_pause}s to {pause_value}s ({option})")
  790. # Emit change signal for QML
  791. self.pauseBetweenPatternsChanged.emit(pause_value)
  792. else:
  793. print(f"⚠️ Unknown pause option: {option}")
  794. # Property for pause between patterns
  795. @Property(int, notify=pauseBetweenPatternsChanged)
  796. def pauseBetweenPatterns(self):
  797. """Get current pause between patterns in seconds"""
  798. return self._pause_between_patterns
  799. # Screen Control Methods
  800. @Slot()
  801. def turnScreenOn(self):
  802. """Turn the screen on and reset activity timer"""
  803. if not self._screen_on:
  804. self._turn_screen_on()
  805. self._reset_activity_timer()
  806. @Slot()
  807. def turnScreenOff(self):
  808. """Turn the screen off"""
  809. self._turn_screen_off()
  810. # Start touch monitoring after manual screen off
  811. QTimer.singleShot(1000, self._start_touch_monitoring) # 1 second delay
  812. @Slot()
  813. def resetActivityTimer(self):
  814. """Reset the activity timer (call on user interaction)"""
  815. self._reset_activity_timer()
  816. if not self._screen_on:
  817. self._turn_screen_on()
  818. def _turn_screen_on(self):
  819. """Internal method to turn screen on"""
  820. with self._screen_transition_lock:
  821. # Debounce: Don't turn on if we just changed state
  822. time_since_change = time.time() - self._last_screen_change
  823. if time_since_change < 2.0: # 2 second debounce
  824. print(f"🖥️ Screen state change blocked (debounce: {time_since_change:.1f}s < 2s)")
  825. return
  826. if self._screen_on:
  827. print("🖥️ Screen already ON, skipping")
  828. return
  829. try:
  830. # Use the working screen-on script if available
  831. screen_on_script = Path('/usr/local/bin/screen-on')
  832. if screen_on_script.exists():
  833. result = subprocess.run(['sudo', '/usr/local/bin/screen-on'],
  834. capture_output=True, text=True, timeout=5)
  835. if result.returncode == 0:
  836. print("🖥️ Screen turned ON (screen-on script)")
  837. else:
  838. print(f"⚠️ screen-on script failed: {result.stderr}")
  839. else:
  840. # Fallback: Manual control matching the script
  841. # Unblank framebuffer and restore backlight
  842. max_brightness = 255
  843. try:
  844. result = subprocess.run(['cat', '/sys/class/backlight/*/max_brightness'],
  845. shell=True, capture_output=True, text=True, timeout=2)
  846. if result.returncode == 0 and result.stdout.strip():
  847. max_brightness = int(result.stdout.strip())
  848. except:
  849. pass
  850. subprocess.run(['sudo', 'sh', '-c',
  851. f'echo 0 > /sys/class/graphics/fb0/blank && echo {max_brightness} > /sys/class/backlight/*/brightness'],
  852. check=False, timeout=5)
  853. print(f"🖥️ Screen turned ON (manual, brightness: {max_brightness})")
  854. self._screen_on = True
  855. self._last_screen_change = time.time()
  856. self.screenStateChanged.emit(True)
  857. except Exception as e:
  858. print(f"❌ Failed to turn screen on: {e}")
  859. def _turn_screen_off(self):
  860. """Internal method to turn screen off"""
  861. print("🖥️ _turn_screen_off() called")
  862. with self._screen_transition_lock:
  863. # Debounce: Don't turn off if we just changed state
  864. time_since_change = time.time() - self._last_screen_change
  865. if time_since_change < 2.0: # 2 second debounce
  866. print(f"🖥️ Screen state change blocked (debounce: {time_since_change:.1f}s < 2s)")
  867. return
  868. if not self._screen_on:
  869. print("🖥️ Screen already OFF, skipping")
  870. return
  871. try:
  872. # Use the working screen-off script if available
  873. screen_off_script = Path('/usr/local/bin/screen-off')
  874. print(f"🖥️ Checking for screen-off script at: {screen_off_script}")
  875. print(f"🖥️ Script exists: {screen_off_script.exists()}")
  876. if screen_off_script.exists():
  877. print("🖥️ Executing screen-off script...")
  878. result = subprocess.run(['sudo', '/usr/local/bin/screen-off'],
  879. capture_output=True, text=True, timeout=10)
  880. print(f"🖥️ Script return code: {result.returncode}")
  881. if result.stdout:
  882. print(f"🖥️ Script stdout: {result.stdout}")
  883. if result.stderr:
  884. print(f"🖥️ Script stderr: {result.stderr}")
  885. if result.returncode == 0:
  886. print("✅ Screen turned OFF (screen-off script)")
  887. else:
  888. print(f"⚠️ screen-off script failed: return code {result.returncode}")
  889. else:
  890. print("🖥️ Using manual screen control...")
  891. # Fallback: Manual control matching the script
  892. # Blank framebuffer and turn off backlight
  893. subprocess.run(['sudo', 'sh', '-c',
  894. 'echo 0 > /sys/class/backlight/*/brightness && echo 1 > /sys/class/graphics/fb0/blank'],
  895. check=False, timeout=5)
  896. print("🖥️ Screen turned OFF (manual)")
  897. self._screen_on = False
  898. self._last_screen_change = time.time()
  899. self.screenStateChanged.emit(False)
  900. print("🖥️ Screen state set to OFF, signal emitted")
  901. except Exception as e:
  902. print(f"❌ Failed to turn screen off: {e}")
  903. import traceback
  904. traceback.print_exc()
  905. def _reset_activity_timer(self):
  906. """Reset the last activity timestamp"""
  907. old_time = self._last_activity
  908. self._last_activity = time.time()
  909. time_since_last = self._last_activity - old_time
  910. if time_since_last > 1: # Only log if it's been more than 1 second
  911. print(f"🖥️ Activity detected - timer reset (was idle for {time_since_last:.1f}s)")
  912. def _check_screen_timeout(self):
  913. """Check if screen should be turned off due to inactivity"""
  914. if self._screen_on and self._screen_timeout > 0: # Only check if timeout is enabled
  915. idle_time = time.time() - self._last_activity
  916. # Log every 10 seconds when getting close to timeout
  917. if idle_time > self._screen_timeout - 10 and idle_time % 10 < 1:
  918. print(f"🖥️ Screen idle for {idle_time:.0f}s (timeout at {self._screen_timeout}s)")
  919. if idle_time > self._screen_timeout:
  920. print(f"🖥️ Screen timeout reached! Idle for {idle_time:.0f}s (timeout: {self._screen_timeout}s)")
  921. self._turn_screen_off()
  922. # Add delay before starting touch monitoring to avoid catching residual events
  923. QTimer.singleShot(1000, self._start_touch_monitoring) # 1 second delay
  924. # If timeout is 0 (Never), screen stays on indefinitely
  925. def _start_touch_monitoring(self):
  926. """Start monitoring touch input for wake-up"""
  927. if self._touch_monitor_thread is None or not self._touch_monitor_thread.is_alive():
  928. self._touch_monitor_thread = threading.Thread(target=self._monitor_touch_input, daemon=True)
  929. self._touch_monitor_thread.start()
  930. def _monitor_touch_input(self):
  931. """Monitor touch input to wake up the screen"""
  932. print("👆 Starting touch monitoring for wake-up")
  933. # Add delay to let any residual touch events clear
  934. time.sleep(2)
  935. # Flush touch device to clear any buffered events
  936. try:
  937. # Find and flush touch device
  938. for i in range(5):
  939. device = f'/dev/input/event{i}'
  940. if Path(device).exists():
  941. try:
  942. # Read and discard any pending events
  943. with open(device, 'rb') as f:
  944. import fcntl
  945. import os
  946. fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
  947. while True:
  948. try:
  949. f.read(24) # Standard input_event size
  950. except:
  951. break
  952. print(f"👆 Flushed touch device: {device}")
  953. break
  954. except:
  955. continue
  956. except Exception as e:
  957. print(f"👆 Could not flush touch device: {e}")
  958. print("👆 Touch monitoring active")
  959. try:
  960. # Use external touch monitor script if available - but only if not too sensitive
  961. touch_monitor_script = Path('/usr/local/bin/touch-monitor')
  962. use_script = touch_monitor_script.exists() and hasattr(self, '_use_touch_script') and self._use_touch_script
  963. if use_script:
  964. print("👆 Using touch-monitor script")
  965. # Add extra delay for script-based monitoring since it's more sensitive
  966. time.sleep(3)
  967. print("👆 Starting touch-monitor script after flush delay")
  968. process = subprocess.Popen(['sudo', '/usr/local/bin/touch-monitor'],
  969. stdout=subprocess.PIPE,
  970. stderr=subprocess.PIPE)
  971. # Wait for script to detect touch and wake screen
  972. while not self._screen_on:
  973. if process.poll() is not None: # Script exited (touch detected)
  974. print("👆 Touch detected by monitor script")
  975. self._turn_screen_on()
  976. self._reset_activity_timer()
  977. break
  978. time.sleep(0.1)
  979. if process.poll() is None:
  980. process.terminate()
  981. else:
  982. # Fallback: Direct monitoring
  983. # Find touch input device
  984. touch_device = None
  985. for i in range(5): # Check event0 through event4
  986. device = f'/dev/input/event{i}'
  987. if Path(device).exists():
  988. # Check if it's a touch device
  989. try:
  990. info = subprocess.run(['udevadm', 'info', '--query=all', f'--name={device}'],
  991. capture_output=True, text=True, timeout=2)
  992. if 'touch' in info.stdout.lower() or 'ft5406' in info.stdout.lower():
  993. touch_device = device
  994. break
  995. except:
  996. pass
  997. if not touch_device:
  998. touch_device = '/dev/input/event0' # Default fallback
  999. print(f"👆 Monitoring touch device: {touch_device}")
  1000. # Try evtest first (more responsive to single taps)
  1001. evtest_available = subprocess.run(['which', 'evtest'],
  1002. capture_output=True).returncode == 0
  1003. if evtest_available:
  1004. # Use evtest which is more sensitive to single touches
  1005. print("👆 Using evtest for touch detection")
  1006. process = subprocess.Popen(['sudo', 'evtest', touch_device],
  1007. stdout=subprocess.PIPE,
  1008. stderr=subprocess.DEVNULL,
  1009. text=True)
  1010. # Wait for any event line
  1011. while not self._screen_on:
  1012. try:
  1013. line = process.stdout.readline()
  1014. if line and 'Event:' in line:
  1015. print("👆 Touch detected via evtest - waking screen")
  1016. process.terminate()
  1017. self._turn_screen_on()
  1018. self._reset_activity_timer()
  1019. break
  1020. except:
  1021. pass
  1022. if process.poll() is not None:
  1023. break
  1024. time.sleep(0.01) # Small sleep to prevent CPU spinning
  1025. else:
  1026. # Fallback: Use cat with single byte read (more responsive)
  1027. print("👆 Using cat for touch detection")
  1028. process = subprocess.Popen(['sudo', 'cat', touch_device],
  1029. stdout=subprocess.PIPE,
  1030. stderr=subprocess.DEVNULL)
  1031. # Wait for any data (even 1 byte indicates touch)
  1032. while not self._screen_on:
  1033. try:
  1034. # Non-blocking check for data
  1035. import select
  1036. ready, _, _ = select.select([process.stdout], [], [], 0.1)
  1037. if ready:
  1038. data = process.stdout.read(1) # Read just 1 byte
  1039. if data:
  1040. print("👆 Touch detected - waking screen")
  1041. process.terminate()
  1042. self._turn_screen_on()
  1043. self._reset_activity_timer()
  1044. break
  1045. except:
  1046. pass
  1047. # Check if screen was turned on by other means
  1048. if self._screen_on:
  1049. process.terminate()
  1050. break
  1051. time.sleep(0.1)
  1052. except Exception as e:
  1053. print(f"❌ Error monitoring touch input: {e}")
  1054. print("👆 Touch monitoring stopped")