backend.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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._api_call("/send_home"))
  583. @Slot()
  584. def moveToCenter(self):
  585. print("🎯 Moving to center...")
  586. asyncio.create_task(self._api_call("/move_to_center"))
  587. @Slot()
  588. def moveToPerimeter(self):
  589. print("⭕ Moving to perimeter...")
  590. asyncio.create_task(self._api_call("/move_to_perimeter"))
  591. # Speed Control
  592. @Slot(int)
  593. def setSpeed(self, speed):
  594. print(f"⚡ Setting speed to: {speed}")
  595. asyncio.create_task(self._set_speed(speed))
  596. async def _set_speed(self, speed):
  597. if not self.session:
  598. self.errorOccurred.emit("Backend not ready")
  599. return
  600. try:
  601. async with self.session.post(f"{self.base_url}/set_speed", json={"speed": speed}) as resp:
  602. if resp.status == 200:
  603. print(f"✅ Speed set to {speed}")
  604. self._current_speed = speed
  605. self.speedChanged.emit(speed)
  606. else:
  607. response_text = await resp.text()
  608. print(f"❌ Failed to set speed: {resp.status} - {response_text}")
  609. except Exception as e:
  610. print(f"💥 Exception setting speed: {e}")
  611. self.errorOccurred.emit(str(e))
  612. # Auto Play on Boot Setting
  613. @Slot(bool)
  614. def setAutoPlayOnBoot(self, enabled):
  615. print(f"🚀 Setting auto play on boot: {enabled}")
  616. asyncio.create_task(self._set_auto_play_on_boot(enabled))
  617. async def _set_auto_play_on_boot(self, enabled):
  618. if not self.session:
  619. self.errorOccurred.emit("Backend not ready")
  620. return
  621. try:
  622. # Use the kiosk mode API endpoint for auto-play on boot
  623. async with self.session.post(f"{self.base_url}/api/kiosk-mode", json={"enabled": enabled}) as resp:
  624. if resp.status == 200:
  625. print(f"✅ Auto play on boot set to {enabled}")
  626. self._auto_play_on_boot = enabled
  627. else:
  628. response_text = await resp.text()
  629. print(f"❌ Failed to set auto play: {resp.status} - {response_text}")
  630. except Exception as e:
  631. print(f"💥 Exception setting auto play: {e}")
  632. self.errorOccurred.emit(str(e))
  633. # Note: Screen timeout is now managed locally in touch_settings.json
  634. # The main application doesn't have a kiosk-mode endpoint, so we manage this locally
  635. # Load Settings
  636. def _load_local_settings(self):
  637. """Load settings from local JSON file"""
  638. try:
  639. if os.path.exists(self.SETTINGS_FILE):
  640. with open(self.SETTINGS_FILE, 'r') as f:
  641. settings = json.load(f)
  642. screen_timeout = settings.get('screen_timeout', self.DEFAULT_SCREEN_TIMEOUT)
  643. if isinstance(screen_timeout, (int, float)) and screen_timeout >= 0:
  644. self._screen_timeout = int(screen_timeout)
  645. if screen_timeout == 0:
  646. print(f"🖥️ Loaded screen timeout from local settings: Never (0s)")
  647. else:
  648. print(f"🖥️ Loaded screen timeout from local settings: {self._screen_timeout}s")
  649. else:
  650. print(f"⚠️ Invalid screen timeout in settings, using default: {self.DEFAULT_SCREEN_TIMEOUT}s")
  651. else:
  652. print(f"📄 No local settings file found, creating with defaults")
  653. self._save_local_settings()
  654. except Exception as e:
  655. print(f"❌ Error loading local settings: {e}, using defaults")
  656. self._screen_timeout = self.DEFAULT_SCREEN_TIMEOUT
  657. def _save_local_settings(self):
  658. """Save settings to local JSON file"""
  659. try:
  660. settings = {
  661. 'screen_timeout': self._screen_timeout,
  662. 'version': '1.0'
  663. }
  664. with open(self.SETTINGS_FILE, 'w') as f:
  665. json.dump(settings, f, indent=2)
  666. print(f"💾 Saved local settings: screen_timeout={self._screen_timeout}s")
  667. except Exception as e:
  668. print(f"❌ Error saving local settings: {e}")
  669. @Slot()
  670. def loadControlSettings(self):
  671. print("📋 Loading control settings...")
  672. asyncio.create_task(self._load_settings())
  673. async def _load_settings(self):
  674. if not self.session:
  675. print("⚠️ Session not ready for loading settings")
  676. return
  677. try:
  678. # Load auto play setting from the working endpoint
  679. timeout = aiohttp.ClientTimeout(total=5) # 5 second timeout
  680. async with self.session.get(f"{self.base_url}/api/auto_play-mode", timeout=timeout) as resp:
  681. if resp.status == 200:
  682. data = await resp.json()
  683. self._auto_play_on_boot = data.get("enabled", False)
  684. print(f"🚀 Loaded auto play setting: {self._auto_play_on_boot}")
  685. # Note: Screen timeout is managed locally, not from server
  686. # Serial status will be handled by WebSocket updates automatically
  687. # But we still load the initial port info if connected
  688. async with self.session.get(f"{self.base_url}/serial_status", timeout=timeout) as resp:
  689. if resp.status == 200:
  690. data = await resp.json()
  691. initial_connected = data.get("connected", False)
  692. current_port = data.get("port", "")
  693. print(f"🔌 Initial serial status: connected={initial_connected}, port={current_port}")
  694. # Only update if WebSocket hasn't already set this
  695. if initial_connected and current_port and not self._current_port:
  696. self._current_port = current_port
  697. self.currentPortChanged.emit(current_port)
  698. # Set initial connection status (WebSocket will take over from here)
  699. if self._serial_connected != initial_connected:
  700. self._serial_connected = initial_connected
  701. self.serialConnectionChanged.emit(initial_connected)
  702. print("✅ Settings loaded - WebSocket will handle real-time updates")
  703. self.settingsLoaded.emit()
  704. except aiohttp.ClientConnectorError as e:
  705. print(f"⚠️ Cannot connect to backend at {self.base_url}: {e}")
  706. # Don't emit error - this is expected when backend is down
  707. # WebSocket will handle reconnection
  708. except asyncio.TimeoutError:
  709. print(f"⏰ Timeout loading settings from {self.base_url}")
  710. # Don't emit error - expected when backend is slow/down
  711. except Exception as e:
  712. print(f"💥 Unexpected error loading settings: {e}")
  713. # Only emit error for unexpected issues
  714. if "ssl" not in str(e).lower():
  715. self.errorOccurred.emit(str(e))
  716. # Screen Management Properties
  717. @Property(bool, notify=screenStateChanged)
  718. def screenOn(self):
  719. return self._screen_on
  720. @Property(int, notify=screenTimeoutChanged)
  721. def screenTimeout(self):
  722. return self._screen_timeout
  723. @screenTimeout.setter
  724. def setScreenTimeout(self, timeout):
  725. if self._screen_timeout != timeout:
  726. old_timeout = self._screen_timeout
  727. self._screen_timeout = timeout
  728. print(f"🖥️ Screen timeout changed from {old_timeout}s to {timeout}s")
  729. # Save to local settings
  730. self._save_local_settings()
  731. # Emit change signal for QML
  732. self.screenTimeoutChanged.emit(timeout)
  733. @Slot(result='QStringList')
  734. def getScreenTimeoutOptions(self):
  735. """Get list of screen timeout options for QML"""
  736. return list(self.TIMEOUT_OPTIONS.keys())
  737. @Slot(result=str)
  738. def getCurrentScreenTimeoutOption(self):
  739. """Get current screen timeout as option string"""
  740. current_timeout = self._screen_timeout
  741. for option, value in self.TIMEOUT_OPTIONS.items():
  742. if value == current_timeout:
  743. return option
  744. # If custom value, return closest match or custom description
  745. if current_timeout == 0:
  746. return "Never"
  747. elif current_timeout < 60:
  748. return f"{current_timeout} seconds"
  749. elif current_timeout < 3600:
  750. minutes = current_timeout // 60
  751. return f"{minutes} minute{'s' if minutes != 1 else ''}"
  752. else:
  753. hours = current_timeout // 3600
  754. return f"{hours} hour{'s' if hours != 1 else ''}"
  755. @Slot(str)
  756. def setScreenTimeoutByOption(self, option):
  757. """Set screen timeout by option string"""
  758. if option in self.TIMEOUT_OPTIONS:
  759. timeout_value = self.TIMEOUT_OPTIONS[option]
  760. # Don't call the setter method, just assign to trigger the property setter
  761. if self._screen_timeout != timeout_value:
  762. old_timeout = self._screen_timeout
  763. self._screen_timeout = timeout_value
  764. print(f"🖥️ Screen timeout changed from {old_timeout}s to {timeout_value}s ({option})")
  765. # Save to local settings
  766. self._save_local_settings()
  767. # Emit change signal for QML
  768. self.screenTimeoutChanged.emit(timeout_value)
  769. else:
  770. print(f"⚠️ Unknown timeout option: {option}")
  771. @Slot(result='QStringList')
  772. def getSpeedOptions(self):
  773. """Get list of speed options for QML"""
  774. return list(self.SPEED_OPTIONS.keys())
  775. @Slot(result=str)
  776. def getCurrentSpeedOption(self):
  777. """Get current speed as option string"""
  778. current_speed = self._current_speed
  779. for option, value in self.SPEED_OPTIONS.items():
  780. if value == current_speed:
  781. return option
  782. # If custom value, return as string
  783. return str(current_speed)
  784. @Slot(str)
  785. def setSpeedByOption(self, option):
  786. """Set speed by option string"""
  787. if option in self.SPEED_OPTIONS:
  788. speed_value = self.SPEED_OPTIONS[option]
  789. # Don't call setter method, just assign directly
  790. if self._current_speed != speed_value:
  791. old_speed = self._current_speed
  792. self._current_speed = speed_value
  793. print(f"⚡ Speed changed from {old_speed} to {speed_value} ({option})")
  794. # Send to main application
  795. asyncio.create_task(self._set_speed_async(speed_value))
  796. # Emit change signal for QML
  797. self.speedChanged.emit(speed_value)
  798. else:
  799. print(f"⚠️ Unknown speed option: {option}")
  800. async def _set_speed_async(self, speed):
  801. """Send speed to main application asynchronously"""
  802. if not self.session:
  803. return
  804. try:
  805. async with self.session.post(f"{self.base_url}/set_speed", json={"speed": speed}) as resp:
  806. if resp.status == 200:
  807. print(f"✅ Speed set successfully: {speed}")
  808. else:
  809. print(f"❌ Failed to set speed: {resp.status}")
  810. except Exception as e:
  811. print(f"💥 Exception setting speed: {e}")
  812. # Pause Between Patterns Methods
  813. @Slot(result='QStringList')
  814. def getPauseOptions(self):
  815. """Get list of pause between patterns options for QML"""
  816. return list(self.PAUSE_OPTIONS.keys())
  817. @Slot(result=str)
  818. def getCurrentPauseOption(self):
  819. """Get current pause between patterns as option string"""
  820. current_pause = self._pause_between_patterns
  821. for option, value in self.PAUSE_OPTIONS.items():
  822. if value == current_pause:
  823. return option
  824. # If custom value, return descriptive string
  825. if current_pause == 0:
  826. return "0s"
  827. elif current_pause < 60:
  828. return f"{current_pause}s"
  829. elif current_pause < 3600:
  830. minutes = current_pause // 60
  831. return f"{minutes} min"
  832. else:
  833. hours = current_pause // 3600
  834. return f"{hours} hour"
  835. @Slot(str)
  836. def setPauseByOption(self, option):
  837. """Set pause between patterns by option string"""
  838. if option in self.PAUSE_OPTIONS:
  839. pause_value = self.PAUSE_OPTIONS[option]
  840. if self._pause_between_patterns != pause_value:
  841. old_pause = self._pause_between_patterns
  842. self._pause_between_patterns = pause_value
  843. print(f"⏸️ Pause between patterns changed from {old_pause}s to {pause_value}s ({option})")
  844. # Emit change signal for QML
  845. self.pauseBetweenPatternsChanged.emit(pause_value)
  846. else:
  847. print(f"⚠️ Unknown pause option: {option}")
  848. # Property for pause between patterns
  849. @Property(int, notify=pauseBetweenPatternsChanged)
  850. def pauseBetweenPatterns(self):
  851. """Get current pause between patterns in seconds"""
  852. return self._pause_between_patterns
  853. # Screen Control Methods
  854. @Slot()
  855. def turnScreenOn(self):
  856. """Turn the screen on and reset activity timer"""
  857. if not self._screen_on:
  858. self._turn_screen_on()
  859. self._reset_activity_timer()
  860. @Slot()
  861. def turnScreenOff(self):
  862. """Turn the screen off"""
  863. self._turn_screen_off()
  864. # Start touch monitoring after manual screen off
  865. QTimer.singleShot(1000, self._start_touch_monitoring) # 1 second delay
  866. @Slot()
  867. def resetActivityTimer(self):
  868. """Reset the activity timer (call on user interaction)"""
  869. self._reset_activity_timer()
  870. if not self._screen_on:
  871. self._turn_screen_on()
  872. def _turn_screen_on(self):
  873. """Internal method to turn screen on"""
  874. with self._screen_transition_lock:
  875. # Debounce: Don't turn on if we just changed state
  876. time_since_change = time.time() - self._last_screen_change
  877. if time_since_change < 2.0: # 2 second debounce
  878. print(f"🖥️ Screen state change blocked (debounce: {time_since_change:.1f}s < 2s)")
  879. return
  880. if self._screen_on:
  881. print("🖥️ Screen already ON, skipping")
  882. return
  883. try:
  884. # Use the working screen-on script if available
  885. screen_on_script = Path('/usr/local/bin/screen-on')
  886. if screen_on_script.exists():
  887. result = subprocess.run(['sudo', '/usr/local/bin/screen-on'],
  888. capture_output=True, text=True, timeout=5)
  889. if result.returncode == 0:
  890. print("🖥️ Screen turned ON (screen-on script)")
  891. else:
  892. print(f"⚠️ screen-on script failed: {result.stderr}")
  893. else:
  894. # Fallback: Manual control matching the script
  895. # Unblank framebuffer and restore backlight
  896. max_brightness = 255
  897. try:
  898. result = subprocess.run(['cat', '/sys/class/backlight/*/max_brightness'],
  899. shell=True, capture_output=True, text=True, timeout=2)
  900. if result.returncode == 0 and result.stdout.strip():
  901. max_brightness = int(result.stdout.strip())
  902. except:
  903. pass
  904. subprocess.run(['sudo', 'sh', '-c',
  905. f'echo 0 > /sys/class/graphics/fb0/blank && echo {max_brightness} > /sys/class/backlight/*/brightness'],
  906. check=False, timeout=5)
  907. print(f"🖥️ Screen turned ON (manual, brightness: {max_brightness})")
  908. self._screen_on = True
  909. self._last_screen_change = time.time()
  910. self.screenStateChanged.emit(True)
  911. except Exception as e:
  912. print(f"❌ Failed to turn screen on: {e}")
  913. def _turn_screen_off(self):
  914. """Internal method to turn screen off"""
  915. print("🖥️ _turn_screen_off() called")
  916. with self._screen_transition_lock:
  917. # Debounce: Don't turn off if we just changed state
  918. time_since_change = time.time() - self._last_screen_change
  919. if time_since_change < 2.0: # 2 second debounce
  920. print(f"🖥️ Screen state change blocked (debounce: {time_since_change:.1f}s < 2s)")
  921. return
  922. if not self._screen_on:
  923. print("🖥️ Screen already OFF, skipping")
  924. return
  925. try:
  926. # Use the working screen-off script if available
  927. screen_off_script = Path('/usr/local/bin/screen-off')
  928. print(f"🖥️ Checking for screen-off script at: {screen_off_script}")
  929. print(f"🖥️ Script exists: {screen_off_script.exists()}")
  930. if screen_off_script.exists():
  931. print("🖥️ Executing screen-off script...")
  932. result = subprocess.run(['sudo', '/usr/local/bin/screen-off'],
  933. capture_output=True, text=True, timeout=10)
  934. print(f"🖥️ Script return code: {result.returncode}")
  935. if result.stdout:
  936. print(f"🖥️ Script stdout: {result.stdout}")
  937. if result.stderr:
  938. print(f"🖥️ Script stderr: {result.stderr}")
  939. if result.returncode == 0:
  940. print("✅ Screen turned OFF (screen-off script)")
  941. else:
  942. print(f"⚠️ screen-off script failed: return code {result.returncode}")
  943. else:
  944. print("🖥️ Using manual screen control...")
  945. # Fallback: Manual control matching the script
  946. # Blank framebuffer and turn off backlight
  947. subprocess.run(['sudo', 'sh', '-c',
  948. 'echo 0 > /sys/class/backlight/*/brightness && echo 1 > /sys/class/graphics/fb0/blank'],
  949. check=False, timeout=5)
  950. print("🖥️ Screen turned OFF (manual)")
  951. self._screen_on = False
  952. self._last_screen_change = time.time()
  953. self.screenStateChanged.emit(False)
  954. print("🖥️ Screen state set to OFF, signal emitted")
  955. except Exception as e:
  956. print(f"❌ Failed to turn screen off: {e}")
  957. import traceback
  958. traceback.print_exc()
  959. def _reset_activity_timer(self):
  960. """Reset the last activity timestamp"""
  961. old_time = self._last_activity
  962. self._last_activity = time.time()
  963. time_since_last = self._last_activity - old_time
  964. if time_since_last > 1: # Only log if it's been more than 1 second
  965. print(f"🖥️ Activity detected - timer reset (was idle for {time_since_last:.1f}s)")
  966. def _check_screen_timeout(self):
  967. """Check if screen should be turned off due to inactivity"""
  968. if self._screen_on and self._screen_timeout > 0: # Only check if timeout is enabled
  969. idle_time = time.time() - self._last_activity
  970. # Log every 10 seconds when getting close to timeout
  971. if idle_time > self._screen_timeout - 10 and idle_time % 10 < 1:
  972. print(f"🖥️ Screen idle for {idle_time:.0f}s (timeout at {self._screen_timeout}s)")
  973. if idle_time > self._screen_timeout:
  974. print(f"🖥️ Screen timeout reached! Idle for {idle_time:.0f}s (timeout: {self._screen_timeout}s)")
  975. self._turn_screen_off()
  976. # Add delay before starting touch monitoring to avoid catching residual events
  977. QTimer.singleShot(1000, self._start_touch_monitoring) # 1 second delay
  978. # If timeout is 0 (Never), screen stays on indefinitely
  979. def _start_touch_monitoring(self):
  980. """Start monitoring touch input for wake-up"""
  981. if self._touch_monitor_thread is None or not self._touch_monitor_thread.is_alive():
  982. self._touch_monitor_thread = threading.Thread(target=self._monitor_touch_input, daemon=True)
  983. self._touch_monitor_thread.start()
  984. def _monitor_touch_input(self):
  985. """Monitor touch input to wake up the screen"""
  986. print("👆 Starting touch monitoring for wake-up")
  987. # Add delay to let any residual touch events clear
  988. time.sleep(2)
  989. # Flush touch device to clear any buffered events
  990. try:
  991. # Find and flush touch device
  992. for i in range(5):
  993. device = f'/dev/input/event{i}'
  994. if Path(device).exists():
  995. try:
  996. # Read and discard any pending events
  997. with open(device, 'rb') as f:
  998. import fcntl
  999. import os
  1000. fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
  1001. while True:
  1002. try:
  1003. f.read(24) # Standard input_event size
  1004. except:
  1005. break
  1006. print(f"👆 Flushed touch device: {device}")
  1007. break
  1008. except:
  1009. continue
  1010. except Exception as e:
  1011. print(f"👆 Could not flush touch device: {e}")
  1012. print("👆 Touch monitoring active")
  1013. try:
  1014. # Use external touch monitor script if available - but only if not too sensitive
  1015. touch_monitor_script = Path('/usr/local/bin/touch-monitor')
  1016. use_script = touch_monitor_script.exists() and hasattr(self, '_use_touch_script') and self._use_touch_script
  1017. if use_script:
  1018. print("👆 Using touch-monitor script")
  1019. # Add extra delay for script-based monitoring since it's more sensitive
  1020. time.sleep(3)
  1021. print("👆 Starting touch-monitor script after flush delay")
  1022. process = subprocess.Popen(['sudo', '/usr/local/bin/touch-monitor'],
  1023. stdout=subprocess.PIPE,
  1024. stderr=subprocess.PIPE)
  1025. # Wait for script to detect touch and wake screen
  1026. while not self._screen_on:
  1027. if process.poll() is not None: # Script exited (touch detected)
  1028. print("👆 Touch detected by monitor script")
  1029. self._turn_screen_on()
  1030. self._reset_activity_timer()
  1031. break
  1032. time.sleep(0.1)
  1033. if process.poll() is None:
  1034. process.terminate()
  1035. else:
  1036. # Fallback: Direct monitoring
  1037. # Find touch input device
  1038. touch_device = None
  1039. for i in range(5): # Check event0 through event4
  1040. device = f'/dev/input/event{i}'
  1041. if Path(device).exists():
  1042. # Check if it's a touch device
  1043. try:
  1044. info = subprocess.run(['udevadm', 'info', '--query=all', f'--name={device}'],
  1045. capture_output=True, text=True, timeout=2)
  1046. if 'touch' in info.stdout.lower() or 'ft5406' in info.stdout.lower():
  1047. touch_device = device
  1048. break
  1049. except:
  1050. pass
  1051. if not touch_device:
  1052. touch_device = '/dev/input/event0' # Default fallback
  1053. print(f"👆 Monitoring touch device: {touch_device}")
  1054. # Try evtest first (more responsive to single taps)
  1055. evtest_available = subprocess.run(['which', 'evtest'],
  1056. capture_output=True).returncode == 0
  1057. if evtest_available:
  1058. # Use evtest which is more sensitive to single touches
  1059. print("👆 Using evtest for touch detection")
  1060. process = subprocess.Popen(['sudo', 'evtest', touch_device],
  1061. stdout=subprocess.PIPE,
  1062. stderr=subprocess.DEVNULL,
  1063. text=True)
  1064. # Wait for any event line
  1065. while not self._screen_on:
  1066. try:
  1067. line = process.stdout.readline()
  1068. if line and 'Event:' in line:
  1069. print("👆 Touch detected via evtest - waking screen")
  1070. process.terminate()
  1071. self._turn_screen_on()
  1072. self._reset_activity_timer()
  1073. break
  1074. except:
  1075. pass
  1076. if process.poll() is not None:
  1077. break
  1078. time.sleep(0.01) # Small sleep to prevent CPU spinning
  1079. else:
  1080. # Fallback: Use cat with single byte read (more responsive)
  1081. print("👆 Using cat for touch detection")
  1082. process = subprocess.Popen(['sudo', 'cat', touch_device],
  1083. stdout=subprocess.PIPE,
  1084. stderr=subprocess.DEVNULL)
  1085. # Wait for any data (even 1 byte indicates touch)
  1086. while not self._screen_on:
  1087. try:
  1088. # Non-blocking check for data
  1089. import select
  1090. ready, _, _ = select.select([process.stdout], [], [], 0.1)
  1091. if ready:
  1092. data = process.stdout.read(1) # Read just 1 byte
  1093. if data:
  1094. print("👆 Touch detected - waking screen")
  1095. process.terminate()
  1096. self._turn_screen_on()
  1097. self._reset_activity_timer()
  1098. break
  1099. except:
  1100. pass
  1101. # Check if screen was turned on by other means
  1102. if self._screen_on:
  1103. process.terminate()
  1104. break
  1105. time.sleep(0.1)
  1106. except Exception as e:
  1107. print(f"❌ Error monitoring touch input: {e}")
  1108. print("👆 Touch monitoring stopped")
  1109. # ==================== LED Control Methods ====================
  1110. # LED Properties
  1111. @Property(str, notify=ledStatusChanged)
  1112. def ledProvider(self):
  1113. return self._led_provider
  1114. @Property(bool, notify=ledStatusChanged)
  1115. def ledConnected(self):
  1116. return self._led_connected
  1117. @Property(bool, notify=ledStatusChanged)
  1118. def ledPowerOn(self):
  1119. return self._led_power_on
  1120. @Property(int, notify=ledStatusChanged)
  1121. def ledBrightness(self):
  1122. return self._led_brightness
  1123. @Property(list, notify=ledEffectsLoaded)
  1124. def ledEffects(self):
  1125. return self._led_effects
  1126. @Property(list, notify=ledPalettesLoaded)
  1127. def ledPalettes(self):
  1128. return self._led_palettes
  1129. @Property(int, notify=ledStatusChanged)
  1130. def ledCurrentEffect(self):
  1131. return self._led_current_effect
  1132. @Property(int, notify=ledStatusChanged)
  1133. def ledCurrentPalette(self):
  1134. return self._led_current_palette
  1135. @Property(str, notify=ledStatusChanged)
  1136. def ledColor(self):
  1137. return self._led_color
  1138. @Slot()
  1139. def loadLedConfig(self):
  1140. """Load LED configuration from the server"""
  1141. print("💡 Loading LED configuration...")
  1142. asyncio.create_task(self._load_led_config())
  1143. async def _load_led_config(self):
  1144. if not self.session:
  1145. print("⚠️ Session not ready for LED config")
  1146. return
  1147. try:
  1148. timeout = aiohttp.ClientTimeout(total=5)
  1149. async with self.session.get(f"{self.base_url}/get_led_config", timeout=timeout) as resp:
  1150. if resp.status == 200:
  1151. data = await resp.json()
  1152. self._led_provider = data.get("provider", "none")
  1153. print(f"💡 LED provider: {self._led_provider}")
  1154. if self._led_provider == "dw_leds":
  1155. # Load DW LEDs status
  1156. await self._load_led_status()
  1157. await self._load_led_effects()
  1158. await self._load_led_palettes()
  1159. self.ledStatusChanged.emit()
  1160. else:
  1161. print(f"❌ Failed to get LED config: {resp.status}")
  1162. except Exception as e:
  1163. print(f"💥 Exception loading LED config: {e}")
  1164. async def _load_led_status(self):
  1165. """Load current LED status"""
  1166. if not self.session:
  1167. return
  1168. try:
  1169. timeout = aiohttp.ClientTimeout(total=5)
  1170. async with self.session.get(f"{self.base_url}/api/dw_leds/status", timeout=timeout) as resp:
  1171. if resp.status == 200:
  1172. data = await resp.json()
  1173. self._led_connected = data.get("connected", False)
  1174. self._led_power_on = data.get("power_on", False)
  1175. self._led_brightness = data.get("brightness", 100)
  1176. self._led_current_effect = data.get("current_effect", 0)
  1177. self._led_current_palette = data.get("current_palette", 0)
  1178. print(f"💡 LED status: connected={self._led_connected}, power={self._led_power_on}, brightness={self._led_brightness}")
  1179. self.ledStatusChanged.emit()
  1180. except Exception as e:
  1181. print(f"💥 Exception loading LED status: {e}")
  1182. async def _load_led_effects(self):
  1183. """Load available LED effects"""
  1184. if not self.session:
  1185. return
  1186. try:
  1187. timeout = aiohttp.ClientTimeout(total=5)
  1188. async with self.session.get(f"{self.base_url}/api/dw_leds/effects", timeout=timeout) as resp:
  1189. if resp.status == 200:
  1190. data = await resp.json()
  1191. # API returns effects as [[id, name], ...] arrays
  1192. raw_effects = data.get("effects", [])
  1193. # Convert to list of dicts for easier use in QML
  1194. self._led_effects = [{"id": e[0], "name": e[1]} for e in raw_effects if len(e) >= 2]
  1195. print(f"💡 Loaded {len(self._led_effects)} LED effects")
  1196. self.ledEffectsLoaded.emit(self._led_effects)
  1197. except Exception as e:
  1198. print(f"💥 Exception loading LED effects: {e}")
  1199. async def _load_led_palettes(self):
  1200. """Load available LED palettes"""
  1201. if not self.session:
  1202. return
  1203. try:
  1204. timeout = aiohttp.ClientTimeout(total=5)
  1205. async with self.session.get(f"{self.base_url}/api/dw_leds/palettes", timeout=timeout) as resp:
  1206. if resp.status == 200:
  1207. data = await resp.json()
  1208. # API returns palettes as [[id, name], ...] arrays
  1209. raw_palettes = data.get("palettes", [])
  1210. # Convert to list of dicts for easier use in QML
  1211. self._led_palettes = [{"id": p[0], "name": p[1]} for p in raw_palettes if len(p) >= 2]
  1212. print(f"💡 Loaded {len(self._led_palettes)} LED palettes")
  1213. self.ledPalettesLoaded.emit(self._led_palettes)
  1214. except Exception as e:
  1215. print(f"💥 Exception loading LED palettes: {e}")
  1216. @Slot()
  1217. def refreshLedStatus(self):
  1218. """Refresh LED status from server"""
  1219. print("💡 Refreshing LED status...")
  1220. asyncio.create_task(self._load_led_status())
  1221. @Slot()
  1222. def toggleLedPower(self):
  1223. """Toggle LED power on/off"""
  1224. print("💡 Toggling LED power...")
  1225. asyncio.create_task(self._toggle_led_power())
  1226. async def _toggle_led_power(self):
  1227. if not self.session:
  1228. self.errorOccurred.emit("Backend not ready")
  1229. return
  1230. try:
  1231. async with self.session.post(
  1232. f"{self.base_url}/api/dw_leds/power",
  1233. json={"state": 2} # Toggle
  1234. ) as resp:
  1235. if resp.status == 200:
  1236. data = await resp.json()
  1237. self._led_power_on = data.get("power_on", False)
  1238. self._led_connected = data.get("connected", False)
  1239. print(f"💡 LED power toggled: {self._led_power_on}")
  1240. self.ledStatusChanged.emit()
  1241. else:
  1242. self.errorOccurred.emit(f"Failed to toggle LED power: {resp.status}")
  1243. except Exception as e:
  1244. print(f"💥 Exception toggling LED power: {e}")
  1245. self.errorOccurred.emit(str(e))
  1246. @Slot(bool)
  1247. def setLedPower(self, on):
  1248. """Set LED power state (True=on, False=off)"""
  1249. print(f"💡 Setting LED power: {on}")
  1250. asyncio.create_task(self._set_led_power(on))
  1251. async def _set_led_power(self, on):
  1252. if not self.session:
  1253. self.errorOccurred.emit("Backend not ready")
  1254. return
  1255. try:
  1256. async with self.session.post(
  1257. f"{self.base_url}/api/dw_leds/power",
  1258. json={"state": 1 if on else 0}
  1259. ) as resp:
  1260. if resp.status == 200:
  1261. data = await resp.json()
  1262. self._led_power_on = data.get("power_on", False)
  1263. self._led_connected = data.get("connected", False)
  1264. print(f"💡 LED power set: {self._led_power_on}")
  1265. self.ledStatusChanged.emit()
  1266. else:
  1267. self.errorOccurred.emit(f"Failed to set LED power: {resp.status}")
  1268. except Exception as e:
  1269. print(f"💥 Exception setting LED power: {e}")
  1270. self.errorOccurred.emit(str(e))
  1271. @Slot(int)
  1272. def setLedBrightness(self, value):
  1273. """Set LED brightness (0-100)"""
  1274. print(f"💡 Setting LED brightness: {value}")
  1275. asyncio.create_task(self._set_led_brightness(value))
  1276. async def _set_led_brightness(self, value):
  1277. if not self.session:
  1278. self.errorOccurred.emit("Backend not ready")
  1279. return
  1280. try:
  1281. async with self.session.post(
  1282. f"{self.base_url}/api/dw_leds/brightness",
  1283. json={"value": value}
  1284. ) as resp:
  1285. if resp.status == 200:
  1286. self._led_brightness = value
  1287. print(f"💡 LED brightness set: {value}")
  1288. self.ledStatusChanged.emit()
  1289. else:
  1290. self.errorOccurred.emit(f"Failed to set brightness: {resp.status}")
  1291. except Exception as e:
  1292. print(f"💥 Exception setting LED brightness: {e}")
  1293. self.errorOccurred.emit(str(e))
  1294. @Slot(int, int, int)
  1295. def setLedColor(self, r, g, b):
  1296. """Set LED color using RGB values"""
  1297. print(f"💡 Setting LED color: RGB({r}, {g}, {b})")
  1298. asyncio.create_task(self._set_led_color(r, g, b))
  1299. async def _set_led_color(self, r, g, b):
  1300. if not self.session:
  1301. self.errorOccurred.emit("Backend not ready")
  1302. return
  1303. try:
  1304. async with self.session.post(
  1305. f"{self.base_url}/api/dw_leds/color",
  1306. json={"color": [r, g, b]}
  1307. ) as resp:
  1308. if resp.status == 200:
  1309. self._led_color = f"#{r:02x}{g:02x}{b:02x}"
  1310. print(f"💡 LED color set: {self._led_color}")
  1311. self.ledStatusChanged.emit()
  1312. else:
  1313. self.errorOccurred.emit(f"Failed to set color: {resp.status}")
  1314. except Exception as e:
  1315. print(f"💥 Exception setting LED color: {e}")
  1316. self.errorOccurred.emit(str(e))
  1317. @Slot(str)
  1318. def setLedColorHex(self, hexColor):
  1319. """Set LED color using hex string (e.g., '#ff0000')"""
  1320. # Parse hex color
  1321. hexColor = hexColor.lstrip('#')
  1322. if len(hexColor) == 6:
  1323. r = int(hexColor[0:2], 16)
  1324. g = int(hexColor[2:4], 16)
  1325. b = int(hexColor[4:6], 16)
  1326. self.setLedColor(r, g, b)
  1327. else:
  1328. print(f"⚠️ Invalid hex color: {hexColor}")
  1329. @Slot(int)
  1330. def setLedEffect(self, effectId):
  1331. """Set LED effect by ID"""
  1332. print(f"💡 Setting LED effect: {effectId}")
  1333. asyncio.create_task(self._set_led_effect(effectId))
  1334. async def _set_led_effect(self, effectId):
  1335. if not self.session:
  1336. self.errorOccurred.emit("Backend not ready")
  1337. return
  1338. try:
  1339. async with self.session.post(
  1340. f"{self.base_url}/api/dw_leds/effect",
  1341. json={"effect_id": effectId}
  1342. ) as resp:
  1343. if resp.status == 200:
  1344. self._led_current_effect = effectId
  1345. print(f"💡 LED effect set: {effectId}")
  1346. self.ledStatusChanged.emit()
  1347. else:
  1348. self.errorOccurred.emit(f"Failed to set effect: {resp.status}")
  1349. except Exception as e:
  1350. print(f"💥 Exception setting LED effect: {e}")
  1351. self.errorOccurred.emit(str(e))
  1352. @Slot(int)
  1353. def setLedPalette(self, paletteId):
  1354. """Set LED palette by ID"""
  1355. print(f"💡 Setting LED palette: {paletteId}")
  1356. asyncio.create_task(self._set_led_palette(paletteId))
  1357. async def _set_led_palette(self, paletteId):
  1358. if not self.session:
  1359. self.errorOccurred.emit("Backend not ready")
  1360. return
  1361. try:
  1362. async with self.session.post(
  1363. f"{self.base_url}/api/dw_leds/palette",
  1364. json={"palette_id": paletteId}
  1365. ) as resp:
  1366. if resp.status == 200:
  1367. self._led_current_palette = paletteId
  1368. print(f"💡 LED palette set: {paletteId}")
  1369. self.ledStatusChanged.emit()
  1370. else:
  1371. self.errorOccurred.emit(f"Failed to set palette: {resp.status}")
  1372. except Exception as e:
  1373. print(f"💥 Exception setting LED palette: {e}")
  1374. self.errorOccurred.emit(str(e))