1
0

backend.py 55 KB

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