1
0

backend.py 70 KB

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