backend.py 69 KB

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