backend.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  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. }
  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. # Try different preview image extensions - PNG first for kiosk
  341. # First try with .thr suffix (e.g., pattern.thr.png)
  342. for ext in [".png", ".webp", ".jpg", ".jpeg"]:
  343. preview_file = cache_dir / (clean_filename + ext)
  344. print(f"🔍 Looking for preview: {preview_file}")
  345. if preview_file.exists():
  346. print(f"✅ Found preview: {preview_file}")
  347. return str(preview_file.absolute())
  348. # Then try without .thr suffix (e.g., pattern.png)
  349. base_name = clean_filename.replace(".thr", "")
  350. for ext in [".png", ".webp", ".jpg", ".jpeg"]:
  351. preview_file = cache_dir / (base_name + ext)
  352. print(f"🔍 Looking for preview (no .thr): {preview_file}")
  353. if preview_file.exists():
  354. print(f"✅ Found preview: {preview_file}")
  355. return str(preview_file.absolute())
  356. print("❌ No preview image found")
  357. return ""
  358. except Exception as e:
  359. print(f"💥 Exception finding preview: {e}")
  360. return ""
  361. @Slot()
  362. def stopExecution(self):
  363. asyncio.create_task(self._stop_execution())
  364. async def _stop_execution(self):
  365. if not self.session:
  366. self.errorOccurred.emit("Backend not ready")
  367. return
  368. try:
  369. print("🛑 Calling stop_execution endpoint...")
  370. # Add timeout to prevent hanging
  371. timeout = aiohttp.ClientTimeout(total=10) # 10 second timeout
  372. async with self.session.post(f"{self.base_url}/stop_execution", timeout=timeout) as resp:
  373. print(f"🛑 Stop execution response status: {resp.status}")
  374. if resp.status == 200:
  375. response_data = await resp.json()
  376. print(f"🛑 Stop execution response: {response_data}")
  377. self.executionStopped.emit()
  378. else:
  379. print(f"❌ Stop execution failed with status: {resp.status}")
  380. response_text = await resp.text()
  381. self.errorOccurred.emit(f"Stop failed: {resp.status} - {response_text}")
  382. except asyncio.TimeoutError:
  383. print("⏰ Stop execution request timed out")
  384. self.errorOccurred.emit("Stop execution request timed out")
  385. except Exception as e:
  386. print(f"💥 Exception in _stop_execution: {e}")
  387. self.errorOccurred.emit(str(e))
  388. @Slot()
  389. def pauseExecution(self):
  390. print("⏸️ Pausing execution...")
  391. asyncio.create_task(self._api_call("/pause_execution"))
  392. @Slot()
  393. def resumeExecution(self):
  394. print("▶️ Resuming execution...")
  395. asyncio.create_task(self._api_call("/resume_execution"))
  396. @Slot()
  397. def skipPattern(self):
  398. print("⏭️ Skipping pattern...")
  399. asyncio.create_task(self._api_call("/skip_pattern"))
  400. @Slot(str, float, str, str, bool)
  401. def executePlaylist(self, playlistName, pauseTime=0.0, clearPattern="adaptive", runMode="single", shuffle=False):
  402. print(f"🎵 ExecutePlaylist called: playlist='{playlistName}', pauseTime={pauseTime}, clearPattern='{clearPattern}', runMode='{runMode}', shuffle={shuffle}")
  403. asyncio.create_task(self._execute_playlist(playlistName, pauseTime, clearPattern, runMode, shuffle))
  404. async def _execute_playlist(self, playlistName, pauseTime, clearPattern, runMode, shuffle):
  405. if not self.session:
  406. print("❌ Backend session not ready")
  407. self.errorOccurred.emit("Backend not ready, please try again")
  408. return
  409. try:
  410. request_data = {
  411. "playlist_name": playlistName,
  412. "pause_time": pauseTime,
  413. "clear_pattern": clearPattern,
  414. "run_mode": runMode,
  415. "shuffle": shuffle
  416. }
  417. print(f"🔄 Making HTTP POST to: {self.base_url}/run_playlist")
  418. print(f"📝 Request payload: {request_data}")
  419. async with self.session.post(
  420. f"{self.base_url}/run_playlist",
  421. json=request_data
  422. ) as resp:
  423. print(f"📡 Response status: {resp.status}")
  424. response_text = await resp.text()
  425. print(f"📄 Response body: {response_text}")
  426. if resp.status == 200:
  427. print(f"✅ Playlist execution request successful: {playlistName}")
  428. # The playlist will start executing patterns automatically
  429. # Status updates will come through WebSocket
  430. else:
  431. print(f"❌ Playlist execution failed with status {resp.status}")
  432. self.errorOccurred.emit(f"Failed to execute playlist: {resp.status} - {response_text}")
  433. except Exception as e:
  434. print(f"💥 Exception in _execute_playlist: {e}")
  435. self.errorOccurred.emit(str(e))
  436. async def _api_call(self, endpoint):
  437. if not self.session:
  438. self.errorOccurred.emit("Backend not ready")
  439. return
  440. try:
  441. print(f"📡 Calling API endpoint: {endpoint}")
  442. # Add timeout to prevent hanging
  443. timeout = aiohttp.ClientTimeout(total=10) # 10 second timeout
  444. async with self.session.post(f"{self.base_url}{endpoint}", timeout=timeout) as resp:
  445. print(f"📡 API response status for {endpoint}: {resp.status}")
  446. if resp.status == 200:
  447. response_data = await resp.json()
  448. print(f"📡 API response for {endpoint}: {response_data}")
  449. else:
  450. print(f"❌ API call {endpoint} failed with status: {resp.status}")
  451. response_text = await resp.text()
  452. self.errorOccurred.emit(f"API call failed: {endpoint} - {resp.status} - {response_text}")
  453. except asyncio.TimeoutError:
  454. print(f"⏰ API call {endpoint} timed out")
  455. self.errorOccurred.emit(f"API call {endpoint} timed out")
  456. except Exception as e:
  457. print(f"💥 Exception in API call {endpoint}: {e}")
  458. self.errorOccurred.emit(str(e))
  459. # Serial Port Management
  460. @Slot()
  461. def refreshSerialPorts(self):
  462. print("🔌 Refreshing serial ports...")
  463. asyncio.create_task(self._refresh_serial_ports())
  464. async def _refresh_serial_ports(self):
  465. if not self.session:
  466. self.errorOccurred.emit("Backend not ready")
  467. return
  468. try:
  469. async with self.session.get(f"{self.base_url}/list_serial_ports") as resp:
  470. if resp.status == 200:
  471. # The endpoint returns a list directly, not a dictionary
  472. ports = await resp.json()
  473. self._serial_ports = ports if isinstance(ports, list) else []
  474. print(f"📡 Found serial ports: {self._serial_ports}")
  475. self.serialPortsUpdated.emit(self._serial_ports)
  476. else:
  477. print(f"❌ Failed to get serial ports: {resp.status}")
  478. except Exception as e:
  479. print(f"💥 Exception refreshing serial ports: {e}")
  480. self.errorOccurred.emit(str(e))
  481. @Slot(str)
  482. def connectSerial(self, port):
  483. print(f"🔗 Connecting to serial port: {port}")
  484. asyncio.create_task(self._connect_serial(port))
  485. async def _connect_serial(self, port):
  486. if not self.session:
  487. self.errorOccurred.emit("Backend not ready")
  488. return
  489. try:
  490. async with self.session.post(f"{self.base_url}/connect", json={"port": port}) as resp:
  491. if resp.status == 200:
  492. print(f"✅ Connected to {port}")
  493. self._serial_connected = True
  494. self._current_port = port
  495. self.serialConnectionChanged.emit(True)
  496. self.currentPortChanged.emit(port)
  497. else:
  498. response_text = await resp.text()
  499. print(f"❌ Failed to connect to {port}: {resp.status} - {response_text}")
  500. self.errorOccurred.emit(f"Failed to connect: {response_text}")
  501. except Exception as e:
  502. print(f"💥 Exception connecting to serial: {e}")
  503. self.errorOccurred.emit(str(e))
  504. @Slot()
  505. def disconnectSerial(self):
  506. print("🔌 Disconnecting serial...")
  507. asyncio.create_task(self._disconnect_serial())
  508. async def _disconnect_serial(self):
  509. if not self.session:
  510. self.errorOccurred.emit("Backend not ready")
  511. return
  512. try:
  513. async with self.session.post(f"{self.base_url}/disconnect") as resp:
  514. if resp.status == 200:
  515. print("✅ Disconnected from serial")
  516. self._serial_connected = False
  517. self._current_port = ""
  518. self.serialConnectionChanged.emit(False)
  519. self.currentPortChanged.emit("")
  520. else:
  521. response_text = await resp.text()
  522. print(f"❌ Failed to disconnect: {resp.status} - {response_text}")
  523. except Exception as e:
  524. print(f"💥 Exception disconnecting serial: {e}")
  525. self.errorOccurred.emit(str(e))
  526. # Hardware Movement Controls
  527. @Slot()
  528. def sendHome(self):
  529. print("🏠 Sending home command...")
  530. asyncio.create_task(self._api_call("/send_home"))
  531. @Slot()
  532. def moveToCenter(self):
  533. print("🎯 Moving to center...")
  534. asyncio.create_task(self._api_call("/move_to_center"))
  535. @Slot()
  536. def moveToPerimeter(self):
  537. print("⭕ Moving to perimeter...")
  538. asyncio.create_task(self._api_call("/move_to_perimeter"))
  539. # Speed Control
  540. @Slot(int)
  541. def setSpeed(self, speed):
  542. print(f"⚡ Setting speed to: {speed}")
  543. asyncio.create_task(self._set_speed(speed))
  544. async def _set_speed(self, speed):
  545. if not self.session:
  546. self.errorOccurred.emit("Backend not ready")
  547. return
  548. try:
  549. async with self.session.post(f"{self.base_url}/set_speed", json={"speed": speed}) as resp:
  550. if resp.status == 200:
  551. print(f"✅ Speed set to {speed}")
  552. self._current_speed = speed
  553. self.speedChanged.emit(speed)
  554. else:
  555. response_text = await resp.text()
  556. print(f"❌ Failed to set speed: {resp.status} - {response_text}")
  557. except Exception as e:
  558. print(f"💥 Exception setting speed: {e}")
  559. self.errorOccurred.emit(str(e))
  560. # Auto Play on Boot Setting
  561. @Slot(bool)
  562. def setAutoPlayOnBoot(self, enabled):
  563. print(f"🚀 Setting auto play on boot: {enabled}")
  564. asyncio.create_task(self._set_auto_play_on_boot(enabled))
  565. async def _set_auto_play_on_boot(self, enabled):
  566. if not self.session:
  567. self.errorOccurred.emit("Backend not ready")
  568. return
  569. try:
  570. # Use the kiosk mode API endpoint for auto-play on boot
  571. async with self.session.post(f"{self.base_url}/api/kiosk-mode", json={"enabled": enabled}) as resp:
  572. if resp.status == 200:
  573. print(f"✅ Auto play on boot set to {enabled}")
  574. self._auto_play_on_boot = enabled
  575. else:
  576. response_text = await resp.text()
  577. print(f"❌ Failed to set auto play: {resp.status} - {response_text}")
  578. except Exception as e:
  579. print(f"💥 Exception setting auto play: {e}")
  580. self.errorOccurred.emit(str(e))
  581. # Note: Screen timeout is now managed locally in touch_settings.json
  582. # The main application doesn't have a kiosk-mode endpoint, so we manage this locally
  583. # Load Settings
  584. def _load_local_settings(self):
  585. """Load settings from local JSON file"""
  586. try:
  587. if os.path.exists(self.SETTINGS_FILE):
  588. with open(self.SETTINGS_FILE, 'r') as f:
  589. settings = json.load(f)
  590. screen_timeout = settings.get('screen_timeout', self.DEFAULT_SCREEN_TIMEOUT)
  591. if isinstance(screen_timeout, (int, float)) and screen_timeout >= 0:
  592. self._screen_timeout = int(screen_timeout)
  593. if screen_timeout == 0:
  594. print(f"🖥️ Loaded screen timeout from local settings: Never (0s)")
  595. else:
  596. print(f"🖥️ Loaded screen timeout from local settings: {self._screen_timeout}s")
  597. else:
  598. print(f"⚠️ Invalid screen timeout in settings, using default: {self.DEFAULT_SCREEN_TIMEOUT}s")
  599. else:
  600. print(f"📄 No local settings file found, creating with defaults")
  601. self._save_local_settings()
  602. except Exception as e:
  603. print(f"❌ Error loading local settings: {e}, using defaults")
  604. self._screen_timeout = self.DEFAULT_SCREEN_TIMEOUT
  605. def _save_local_settings(self):
  606. """Save settings to local JSON file"""
  607. try:
  608. settings = {
  609. 'screen_timeout': self._screen_timeout,
  610. 'version': '1.0'
  611. }
  612. with open(self.SETTINGS_FILE, 'w') as f:
  613. json.dump(settings, f, indent=2)
  614. print(f"💾 Saved local settings: screen_timeout={self._screen_timeout}s")
  615. except Exception as e:
  616. print(f"❌ Error saving local settings: {e}")
  617. @Slot()
  618. def loadControlSettings(self):
  619. print("📋 Loading control settings...")
  620. asyncio.create_task(self._load_settings())
  621. async def _load_settings(self):
  622. if not self.session:
  623. print("⚠️ Session not ready for loading settings")
  624. return
  625. try:
  626. # Load auto play setting from the working endpoint
  627. timeout = aiohttp.ClientTimeout(total=5) # 5 second timeout
  628. async with self.session.get(f"{self.base_url}/api/auto_play-mode", timeout=timeout) as resp:
  629. if resp.status == 200:
  630. data = await resp.json()
  631. self._auto_play_on_boot = data.get("enabled", False)
  632. print(f"🚀 Loaded auto play setting: {self._auto_play_on_boot}")
  633. # Note: Screen timeout is managed locally, not from server
  634. # Serial status will be handled by WebSocket updates automatically
  635. # But we still load the initial port info if connected
  636. async with self.session.get(f"{self.base_url}/serial_status", timeout=timeout) as resp:
  637. if resp.status == 200:
  638. data = await resp.json()
  639. initial_connected = data.get("connected", False)
  640. current_port = data.get("port", "")
  641. print(f"🔌 Initial serial status: connected={initial_connected}, port={current_port}")
  642. # Only update if WebSocket hasn't already set this
  643. if initial_connected and current_port and not self._current_port:
  644. self._current_port = current_port
  645. self.currentPortChanged.emit(current_port)
  646. # Set initial connection status (WebSocket will take over from here)
  647. if self._serial_connected != initial_connected:
  648. self._serial_connected = initial_connected
  649. self.serialConnectionChanged.emit(initial_connected)
  650. print("✅ Settings loaded - WebSocket will handle real-time updates")
  651. self.settingsLoaded.emit()
  652. except aiohttp.ClientConnectorError as e:
  653. print(f"⚠️ Cannot connect to backend at {self.base_url}: {e}")
  654. # Don't emit error - this is expected when backend is down
  655. # WebSocket will handle reconnection
  656. except asyncio.TimeoutError:
  657. print(f"⏰ Timeout loading settings from {self.base_url}")
  658. # Don't emit error - expected when backend is slow/down
  659. except Exception as e:
  660. print(f"💥 Unexpected error loading settings: {e}")
  661. # Only emit error for unexpected issues
  662. if "ssl" not in str(e).lower():
  663. self.errorOccurred.emit(str(e))
  664. # Screen Management Properties
  665. @Property(bool, notify=screenStateChanged)
  666. def screenOn(self):
  667. return self._screen_on
  668. @Property(int, notify=screenTimeoutChanged)
  669. def screenTimeout(self):
  670. return self._screen_timeout
  671. @screenTimeout.setter
  672. def setScreenTimeout(self, timeout):
  673. if self._screen_timeout != timeout:
  674. old_timeout = self._screen_timeout
  675. self._screen_timeout = timeout
  676. print(f"🖥️ Screen timeout changed from {old_timeout}s to {timeout}s")
  677. # Save to local settings
  678. self._save_local_settings()
  679. # Emit change signal for QML
  680. self.screenTimeoutChanged.emit(timeout)
  681. @Slot(result='QStringList')
  682. def getScreenTimeoutOptions(self):
  683. """Get list of screen timeout options for QML"""
  684. return list(self.TIMEOUT_OPTIONS.keys())
  685. @Slot(result=str)
  686. def getCurrentScreenTimeoutOption(self):
  687. """Get current screen timeout as option string"""
  688. current_timeout = self._screen_timeout
  689. for option, value in self.TIMEOUT_OPTIONS.items():
  690. if value == current_timeout:
  691. return option
  692. # If custom value, return closest match or custom description
  693. if current_timeout == 0:
  694. return "Never"
  695. elif current_timeout < 60:
  696. return f"{current_timeout} seconds"
  697. elif current_timeout < 3600:
  698. minutes = current_timeout // 60
  699. return f"{minutes} minute{'s' if minutes != 1 else ''}"
  700. else:
  701. hours = current_timeout // 3600
  702. return f"{hours} hour{'s' if hours != 1 else ''}"
  703. @Slot(str)
  704. def setScreenTimeoutByOption(self, option):
  705. """Set screen timeout by option string"""
  706. if option in self.TIMEOUT_OPTIONS:
  707. timeout_value = self.TIMEOUT_OPTIONS[option]
  708. # Don't call the setter method, just assign to trigger the property setter
  709. if self._screen_timeout != timeout_value:
  710. old_timeout = self._screen_timeout
  711. self._screen_timeout = timeout_value
  712. print(f"🖥️ Screen timeout changed from {old_timeout}s to {timeout_value}s ({option})")
  713. # Save to local settings
  714. self._save_local_settings()
  715. # Emit change signal for QML
  716. self.screenTimeoutChanged.emit(timeout_value)
  717. else:
  718. print(f"⚠️ Unknown timeout option: {option}")
  719. @Slot(result='QStringList')
  720. def getSpeedOptions(self):
  721. """Get list of speed options for QML"""
  722. return list(self.SPEED_OPTIONS.keys())
  723. @Slot(result=str)
  724. def getCurrentSpeedOption(self):
  725. """Get current speed as option string"""
  726. current_speed = self._current_speed
  727. for option, value in self.SPEED_OPTIONS.items():
  728. if value == current_speed:
  729. return option
  730. # If custom value, return as string
  731. return str(current_speed)
  732. @Slot(str)
  733. def setSpeedByOption(self, option):
  734. """Set speed by option string"""
  735. if option in self.SPEED_OPTIONS:
  736. speed_value = self.SPEED_OPTIONS[option]
  737. # Don't call setter method, just assign directly
  738. if self._current_speed != speed_value:
  739. old_speed = self._current_speed
  740. self._current_speed = speed_value
  741. print(f"⚡ Speed changed from {old_speed} to {speed_value} ({option})")
  742. # Send to main application
  743. asyncio.create_task(self._set_speed_async(speed_value))
  744. # Emit change signal for QML
  745. self.speedChanged.emit(speed_value)
  746. else:
  747. print(f"⚠️ Unknown speed option: {option}")
  748. async def _set_speed_async(self, speed):
  749. """Send speed to main application asynchronously"""
  750. if not self.session:
  751. return
  752. try:
  753. async with self.session.post(f"{self.base_url}/set_speed", json={"speed": speed}) as resp:
  754. if resp.status == 200:
  755. print(f"✅ Speed set successfully: {speed}")
  756. else:
  757. print(f"❌ Failed to set speed: {resp.status}")
  758. except Exception as e:
  759. print(f"💥 Exception setting speed: {e}")
  760. # Pause Between Patterns Methods
  761. @Slot(result='QStringList')
  762. def getPauseOptions(self):
  763. """Get list of pause between patterns options for QML"""
  764. return list(self.PAUSE_OPTIONS.keys())
  765. @Slot(result=str)
  766. def getCurrentPauseOption(self):
  767. """Get current pause between patterns as option string"""
  768. current_pause = self._pause_between_patterns
  769. for option, value in self.PAUSE_OPTIONS.items():
  770. if value == current_pause:
  771. return option
  772. # If custom value, return descriptive string
  773. if current_pause == 0:
  774. return "0s"
  775. elif current_pause < 60:
  776. return f"{current_pause}s"
  777. elif current_pause < 3600:
  778. minutes = current_pause // 60
  779. return f"{minutes} min"
  780. else:
  781. hours = current_pause // 3600
  782. return f"{hours} hour"
  783. @Slot(str)
  784. def setPauseByOption(self, option):
  785. """Set pause between patterns by option string"""
  786. if option in self.PAUSE_OPTIONS:
  787. pause_value = self.PAUSE_OPTIONS[option]
  788. if self._pause_between_patterns != pause_value:
  789. old_pause = self._pause_between_patterns
  790. self._pause_between_patterns = pause_value
  791. print(f"⏸️ Pause between patterns changed from {old_pause}s to {pause_value}s ({option})")
  792. # Emit change signal for QML
  793. self.pauseBetweenPatternsChanged.emit(pause_value)
  794. else:
  795. print(f"⚠️ Unknown pause option: {option}")
  796. # Property for pause between patterns
  797. @Property(int, notify=pauseBetweenPatternsChanged)
  798. def pauseBetweenPatterns(self):
  799. """Get current pause between patterns in seconds"""
  800. return self._pause_between_patterns
  801. # Screen Control Methods
  802. @Slot()
  803. def turnScreenOn(self):
  804. """Turn the screen on and reset activity timer"""
  805. if not self._screen_on:
  806. self._turn_screen_on()
  807. self._reset_activity_timer()
  808. @Slot()
  809. def turnScreenOff(self):
  810. """Turn the screen off"""
  811. self._turn_screen_off()
  812. # Start touch monitoring after manual screen off
  813. QTimer.singleShot(1000, self._start_touch_monitoring) # 1 second delay
  814. @Slot()
  815. def resetActivityTimer(self):
  816. """Reset the activity timer (call on user interaction)"""
  817. self._reset_activity_timer()
  818. if not self._screen_on:
  819. self._turn_screen_on()
  820. def _turn_screen_on(self):
  821. """Internal method to turn screen on"""
  822. with self._screen_transition_lock:
  823. # Debounce: Don't turn on if we just changed state
  824. time_since_change = time.time() - self._last_screen_change
  825. if time_since_change < 2.0: # 2 second debounce
  826. print(f"🖥️ Screen state change blocked (debounce: {time_since_change:.1f}s < 2s)")
  827. return
  828. if self._screen_on:
  829. print("🖥️ Screen already ON, skipping")
  830. return
  831. try:
  832. # Use the working screen-on script if available
  833. screen_on_script = Path('/usr/local/bin/screen-on')
  834. if screen_on_script.exists():
  835. result = subprocess.run(['sudo', '/usr/local/bin/screen-on'],
  836. capture_output=True, text=True, timeout=5)
  837. if result.returncode == 0:
  838. print("🖥️ Screen turned ON (screen-on script)")
  839. else:
  840. print(f"⚠️ screen-on script failed: {result.stderr}")
  841. else:
  842. # Fallback: Manual control matching the script
  843. # Unblank framebuffer and restore backlight
  844. max_brightness = 255
  845. try:
  846. result = subprocess.run(['cat', '/sys/class/backlight/*/max_brightness'],
  847. shell=True, capture_output=True, text=True, timeout=2)
  848. if result.returncode == 0 and result.stdout.strip():
  849. max_brightness = int(result.stdout.strip())
  850. except:
  851. pass
  852. subprocess.run(['sudo', 'sh', '-c',
  853. f'echo 0 > /sys/class/graphics/fb0/blank && echo {max_brightness} > /sys/class/backlight/*/brightness'],
  854. check=False, timeout=5)
  855. print(f"🖥️ Screen turned ON (manual, brightness: {max_brightness})")
  856. self._screen_on = True
  857. self._last_screen_change = time.time()
  858. self.screenStateChanged.emit(True)
  859. except Exception as e:
  860. print(f"❌ Failed to turn screen on: {e}")
  861. def _turn_screen_off(self):
  862. """Internal method to turn screen off"""
  863. print("🖥️ _turn_screen_off() called")
  864. with self._screen_transition_lock:
  865. # Debounce: Don't turn off if we just changed state
  866. time_since_change = time.time() - self._last_screen_change
  867. if time_since_change < 2.0: # 2 second debounce
  868. print(f"🖥️ Screen state change blocked (debounce: {time_since_change:.1f}s < 2s)")
  869. return
  870. if not self._screen_on:
  871. print("🖥️ Screen already OFF, skipping")
  872. return
  873. try:
  874. # Use the working screen-off script if available
  875. screen_off_script = Path('/usr/local/bin/screen-off')
  876. print(f"🖥️ Checking for screen-off script at: {screen_off_script}")
  877. print(f"🖥️ Script exists: {screen_off_script.exists()}")
  878. if screen_off_script.exists():
  879. print("🖥️ Executing screen-off script...")
  880. result = subprocess.run(['sudo', '/usr/local/bin/screen-off'],
  881. capture_output=True, text=True, timeout=10)
  882. print(f"🖥️ Script return code: {result.returncode}")
  883. if result.stdout:
  884. print(f"🖥️ Script stdout: {result.stdout}")
  885. if result.stderr:
  886. print(f"🖥️ Script stderr: {result.stderr}")
  887. if result.returncode == 0:
  888. print("✅ Screen turned OFF (screen-off script)")
  889. else:
  890. print(f"⚠️ screen-off script failed: return code {result.returncode}")
  891. else:
  892. print("🖥️ Using manual screen control...")
  893. # Fallback: Manual control matching the script
  894. # Blank framebuffer and turn off backlight
  895. subprocess.run(['sudo', 'sh', '-c',
  896. 'echo 0 > /sys/class/backlight/*/brightness && echo 1 > /sys/class/graphics/fb0/blank'],
  897. check=False, timeout=5)
  898. print("🖥️ Screen turned OFF (manual)")
  899. self._screen_on = False
  900. self._last_screen_change = time.time()
  901. self.screenStateChanged.emit(False)
  902. print("🖥️ Screen state set to OFF, signal emitted")
  903. except Exception as e:
  904. print(f"❌ Failed to turn screen off: {e}")
  905. import traceback
  906. traceback.print_exc()
  907. def _reset_activity_timer(self):
  908. """Reset the last activity timestamp"""
  909. old_time = self._last_activity
  910. self._last_activity = time.time()
  911. time_since_last = self._last_activity - old_time
  912. if time_since_last > 1: # Only log if it's been more than 1 second
  913. print(f"🖥️ Activity detected - timer reset (was idle for {time_since_last:.1f}s)")
  914. def _check_screen_timeout(self):
  915. """Check if screen should be turned off due to inactivity"""
  916. if self._screen_on and self._screen_timeout > 0: # Only check if timeout is enabled
  917. idle_time = time.time() - self._last_activity
  918. # Log every 10 seconds when getting close to timeout
  919. if idle_time > self._screen_timeout - 10 and idle_time % 10 < 1:
  920. print(f"🖥️ Screen idle for {idle_time:.0f}s (timeout at {self._screen_timeout}s)")
  921. if idle_time > self._screen_timeout:
  922. print(f"🖥️ Screen timeout reached! Idle for {idle_time:.0f}s (timeout: {self._screen_timeout}s)")
  923. self._turn_screen_off()
  924. # Add delay before starting touch monitoring to avoid catching residual events
  925. QTimer.singleShot(1000, self._start_touch_monitoring) # 1 second delay
  926. # If timeout is 0 (Never), screen stays on indefinitely
  927. def _start_touch_monitoring(self):
  928. """Start monitoring touch input for wake-up"""
  929. if self._touch_monitor_thread is None or not self._touch_monitor_thread.is_alive():
  930. self._touch_monitor_thread = threading.Thread(target=self._monitor_touch_input, daemon=True)
  931. self._touch_monitor_thread.start()
  932. def _monitor_touch_input(self):
  933. """Monitor touch input to wake up the screen"""
  934. print("👆 Starting touch monitoring for wake-up")
  935. # Add delay to let any residual touch events clear
  936. time.sleep(2)
  937. # Flush touch device to clear any buffered events
  938. try:
  939. # Find and flush touch device
  940. for i in range(5):
  941. device = f'/dev/input/event{i}'
  942. if Path(device).exists():
  943. try:
  944. # Read and discard any pending events
  945. with open(device, 'rb') as f:
  946. import fcntl
  947. import os
  948. fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
  949. while True:
  950. try:
  951. f.read(24) # Standard input_event size
  952. except:
  953. break
  954. print(f"👆 Flushed touch device: {device}")
  955. break
  956. except:
  957. continue
  958. except Exception as e:
  959. print(f"👆 Could not flush touch device: {e}")
  960. print("👆 Touch monitoring active")
  961. try:
  962. # Use external touch monitor script if available - but only if not too sensitive
  963. touch_monitor_script = Path('/usr/local/bin/touch-monitor')
  964. use_script = touch_monitor_script.exists() and hasattr(self, '_use_touch_script') and self._use_touch_script
  965. if use_script:
  966. print("👆 Using touch-monitor script")
  967. # Add extra delay for script-based monitoring since it's more sensitive
  968. time.sleep(3)
  969. print("👆 Starting touch-monitor script after flush delay")
  970. process = subprocess.Popen(['sudo', '/usr/local/bin/touch-monitor'],
  971. stdout=subprocess.PIPE,
  972. stderr=subprocess.PIPE)
  973. # Wait for script to detect touch and wake screen
  974. while not self._screen_on:
  975. if process.poll() is not None: # Script exited (touch detected)
  976. print("👆 Touch detected by monitor script")
  977. self._turn_screen_on()
  978. self._reset_activity_timer()
  979. break
  980. time.sleep(0.1)
  981. if process.poll() is None:
  982. process.terminate()
  983. else:
  984. # Fallback: Direct monitoring
  985. # Find touch input device
  986. touch_device = None
  987. for i in range(5): # Check event0 through event4
  988. device = f'/dev/input/event{i}'
  989. if Path(device).exists():
  990. # Check if it's a touch device
  991. try:
  992. info = subprocess.run(['udevadm', 'info', '--query=all', f'--name={device}'],
  993. capture_output=True, text=True, timeout=2)
  994. if 'touch' in info.stdout.lower() or 'ft5406' in info.stdout.lower():
  995. touch_device = device
  996. break
  997. except:
  998. pass
  999. if not touch_device:
  1000. touch_device = '/dev/input/event0' # Default fallback
  1001. print(f"👆 Monitoring touch device: {touch_device}")
  1002. # Try evtest first (more responsive to single taps)
  1003. evtest_available = subprocess.run(['which', 'evtest'],
  1004. capture_output=True).returncode == 0
  1005. if evtest_available:
  1006. # Use evtest which is more sensitive to single touches
  1007. print("👆 Using evtest for touch detection")
  1008. process = subprocess.Popen(['sudo', 'evtest', touch_device],
  1009. stdout=subprocess.PIPE,
  1010. stderr=subprocess.DEVNULL,
  1011. text=True)
  1012. # Wait for any event line
  1013. while not self._screen_on:
  1014. try:
  1015. line = process.stdout.readline()
  1016. if line and 'Event:' in line:
  1017. print("👆 Touch detected via evtest - waking screen")
  1018. process.terminate()
  1019. self._turn_screen_on()
  1020. self._reset_activity_timer()
  1021. break
  1022. except:
  1023. pass
  1024. if process.poll() is not None:
  1025. break
  1026. time.sleep(0.01) # Small sleep to prevent CPU spinning
  1027. else:
  1028. # Fallback: Use cat with single byte read (more responsive)
  1029. print("👆 Using cat for touch detection")
  1030. process = subprocess.Popen(['sudo', 'cat', touch_device],
  1031. stdout=subprocess.PIPE,
  1032. stderr=subprocess.DEVNULL)
  1033. # Wait for any data (even 1 byte indicates touch)
  1034. while not self._screen_on:
  1035. try:
  1036. # Non-blocking check for data
  1037. import select
  1038. ready, _, _ = select.select([process.stdout], [], [], 0.1)
  1039. if ready:
  1040. data = process.stdout.read(1) # Read just 1 byte
  1041. if data:
  1042. print("👆 Touch detected - waking screen")
  1043. process.terminate()
  1044. self._turn_screen_on()
  1045. self._reset_activity_timer()
  1046. break
  1047. except:
  1048. pass
  1049. # Check if screen was turned on by other means
  1050. if self._screen_on:
  1051. process.terminate()
  1052. break
  1053. time.sleep(0.1)
  1054. except Exception as e:
  1055. print(f"❌ Error monitoring touch input: {e}")
  1056. print("👆 Touch monitoring stopped")