1
0

handler.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. """Real MQTT handler implementation."""
  2. import os
  3. import threading
  4. import time
  5. import json
  6. import uuid
  7. from typing import Dict, Callable
  8. import paho.mqtt.client as mqtt
  9. import logging
  10. import asyncio
  11. from .base import BaseMQTTHandler
  12. from modules.core.state import state
  13. from modules.core.pattern_manager import list_theta_rho_files
  14. from modules.core.playlist_manager import list_all_playlists
  15. logger = logging.getLogger(__name__)
  16. class MQTTHandler(BaseMQTTHandler):
  17. """Real implementation of MQTT handler."""
  18. def __init__(self, callback_registry: Dict[str, Callable]):
  19. # MQTT Configuration - prioritize state config over environment variables
  20. # This allows UI configuration to override .env settings
  21. self.broker = state.mqtt_broker if state.mqtt_broker else os.getenv('MQTT_BROKER')
  22. self.port = state.mqtt_port if state.mqtt_port else int(os.getenv('MQTT_PORT', '1883'))
  23. self.username = state.mqtt_username if state.mqtt_username else os.getenv('MQTT_USERNAME')
  24. self.password = state.mqtt_password if state.mqtt_password else os.getenv('MQTT_PASSWORD')
  25. self.status_topic = os.getenv('MQTT_STATUS_TOPIC', 'dune_weaver/status')
  26. self.command_topic = os.getenv('MQTT_COMMAND_TOPIC', 'dune_weaver/command')
  27. self.status_interval = int(os.getenv('MQTT_STATUS_INTERVAL', '30'))
  28. # Store callback registry
  29. self.callback_registry = callback_registry
  30. # Threading control
  31. self.running = False
  32. self.status_thread = None
  33. # Home Assistant MQTT Discovery settings - prioritize state config
  34. self.discovery_prefix = state.mqtt_discovery_prefix if state.mqtt_discovery_prefix else os.getenv('MQTT_DISCOVERY_PREFIX', 'homeassistant')
  35. self.device_name = state.mqtt_device_name if state.mqtt_device_name else os.getenv('HA_DEVICE_NAME', 'Dune Weaver')
  36. self.device_id = state.mqtt_device_id if state.mqtt_device_id else os.getenv('HA_DEVICE_ID', 'dune_weaver')
  37. # MQTT broker-level client identity. If the user hasn't set one explicitly,
  38. # generate a random suffix so two instances can never collide on the same
  39. # client_id and kick each other off the broker in a reconnect loop. The
  40. # device_id prefix keeps the random ID greppable in broker logs.
  41. self.client_id = (
  42. state.mqtt_client_id
  43. or os.getenv('MQTT_CLIENT_ID')
  44. or f"{self.device_id}-{uuid.uuid4().hex[:8]}"
  45. )
  46. # Additional topics for state
  47. self.running_state_topic = f"{self.device_id}/state/running"
  48. self.serial_state_topic = f"{self.device_id}/state/serial"
  49. self.pattern_select_topic = f"{self.device_id}/pattern/set"
  50. self.playlist_select_topic = f"{self.device_id}/playlist/set"
  51. self.speed_topic = f"{self.device_id}/speed/set"
  52. self.completion_topic = f"{self.device_id}/state/completion"
  53. self.time_remaining_topic = f"{self.device_id}/state/time_remaining"
  54. # Screen control topics
  55. self.screen_power_topic = f"{self.device_id}/screen/power/set"
  56. self.screen_brightness_topic = f"{self.device_id}/screen/brightness/set"
  57. # LED control topics
  58. self.led_power_topic = f"{self.device_id}/led/power/set"
  59. self.led_brightness_topic = f"{self.device_id}/led/brightness/set"
  60. self.led_effect_topic = f"{self.device_id}/led/effect/set"
  61. self.led_speed_topic = f"{self.device_id}/led/speed/set"
  62. self.led_intensity_topic = f"{self.device_id}/led/intensity/set"
  63. self.led_color_topic = f"{self.device_id}/led/color/set"
  64. # Store current state
  65. self.current_file = ""
  66. self.is_running_state = False
  67. self.serial_state = ""
  68. self.patterns = []
  69. self.playlists = []
  70. # Track connection state
  71. self._connected = False
  72. # Initialize MQTT client if broker is configured
  73. if self.broker:
  74. self.client = mqtt.Client(client_id=self.client_id)
  75. self.client.on_connect = self.on_connect
  76. self.client.on_disconnect = self.on_disconnect
  77. self.client.on_message = self.on_message
  78. if self.username and self.password:
  79. self.client.username_pw_set(self.username, self.password)
  80. self.state = state
  81. self.state.mqtt_handler = self # Set reference to self in state, needed so that state setters can update the state
  82. # Store the main event loop during initialization
  83. self.main_loop = asyncio.get_event_loop()
  84. def setup_ha_discovery(self):
  85. """Publish Home Assistant MQTT discovery configurations."""
  86. if not self.is_enabled:
  87. return
  88. base_device = {
  89. "identifiers": [self.device_id],
  90. "name": self.device_name,
  91. "model": "Dune Weaver",
  92. "manufacturer": "DIY"
  93. }
  94. # Serial State Sensor
  95. serial_config = {
  96. "name": f"{self.device_name} Serial State",
  97. "unique_id": f"{self.device_id}_serial_state",
  98. "state_topic": self.serial_state_topic,
  99. "device": base_device,
  100. "icon": "mdi:serial-port",
  101. "entity_category": "diagnostic"
  102. }
  103. self._publish_discovery("sensor", "serial_state", serial_config)
  104. # Running State Sensor
  105. running_config = {
  106. "name": f"{self.device_name} Running State",
  107. "unique_id": f"{self.device_id}_running_state",
  108. "state_topic": self.running_state_topic,
  109. "device": base_device,
  110. "icon": "mdi:machine",
  111. "entity_category": "diagnostic"
  112. }
  113. self._publish_discovery("sensor", "running_state", running_config)
  114. # Stop Button
  115. stop_config = {
  116. "name": "Stop pattern execution",
  117. "unique_id": f"{self.device_id}_stop",
  118. "command_topic": f"{self.device_id}/command/stop",
  119. "device": base_device,
  120. "icon": "mdi:stop",
  121. "entity_category": "config"
  122. }
  123. self._publish_discovery("button", "stop", stop_config)
  124. # Pause Button
  125. pause_config = {
  126. "name": "Pause pattern execution",
  127. "unique_id": f"{self.device_id}_pause",
  128. "command_topic": f"{self.device_id}/command/pause",
  129. "state_topic": f"{self.device_id}/command/pause/state",
  130. "device": base_device,
  131. "icon": "mdi:pause",
  132. "entity_category": "config",
  133. "enabled_by_default": True,
  134. "availability": {
  135. "topic": f"{self.device_id}/command/pause/available",
  136. "payload_available": "true",
  137. "payload_not_available": "false"
  138. }
  139. }
  140. self._publish_discovery("button", "pause", pause_config)
  141. # Play Button
  142. play_config = {
  143. "name": "Resume pattern execution",
  144. "unique_id": f"{self.device_id}_play",
  145. "command_topic": f"{self.device_id}/command/play",
  146. "state_topic": f"{self.device_id}/command/play/state",
  147. "device": base_device,
  148. "icon": "mdi:play",
  149. "entity_category": "config",
  150. "enabled_by_default": True,
  151. "availability": {
  152. "topic": f"{self.device_id}/command/play/available",
  153. "payload_available": "true",
  154. "payload_not_available": "false"
  155. }
  156. }
  157. self._publish_discovery("button", "play", play_config)
  158. # Skip Button
  159. skip_config = {
  160. "name": "Skip to next pattern",
  161. "unique_id": f"{self.device_id}_skip",
  162. "command_topic": f"{self.device_id}/command/skip",
  163. "device": base_device,
  164. "icon": "mdi:skip-next",
  165. "entity_category": "config",
  166. "enabled_by_default": True,
  167. "availability": {
  168. "topic": f"{self.device_id}/command/skip/available",
  169. "payload_available": "true",
  170. "payload_not_available": "false"
  171. }
  172. }
  173. self._publish_discovery("button", "skip", skip_config)
  174. # Speed Control
  175. speed_config = {
  176. "name": f"{self.device_name} Speed",
  177. "unique_id": f"{self.device_id}_speed",
  178. "command_topic": self.speed_topic,
  179. "state_topic": f"{self.speed_topic}/state",
  180. "device": base_device,
  181. "icon": "mdi:speedometer",
  182. "mode": "box",
  183. "min": 50,
  184. "max": 2000,
  185. "step": 50
  186. }
  187. self._publish_discovery("number", "speed", speed_config)
  188. # Pattern Select
  189. pattern_config = {
  190. "name": f"{self.device_name} Pattern",
  191. "unique_id": f"{self.device_id}_pattern",
  192. "command_topic": self.pattern_select_topic,
  193. "state_topic": f"{self.pattern_select_topic}/state",
  194. "options": self.patterns,
  195. "device": base_device,
  196. "icon": "mdi:draw"
  197. }
  198. self._publish_discovery("select", "pattern", pattern_config)
  199. # Playlist Select
  200. playlist_config = {
  201. "name": f"{self.device_name} Playlist",
  202. "unique_id": f"{self.device_id}_playlist",
  203. "command_topic": self.playlist_select_topic,
  204. "state_topic": f"{self.playlist_select_topic}/state",
  205. "options": self.playlists,
  206. "device": base_device,
  207. "icon": "mdi:playlist-play"
  208. }
  209. self._publish_discovery("select", "playlist", playlist_config)
  210. # Playlist Run Mode Select
  211. playlist_mode_config = {
  212. "name": f"{self.device_name} Playlist Mode",
  213. "unique_id": f"{self.device_id}_playlist_mode",
  214. "command_topic": f"{self.device_id}/playlist/mode/set",
  215. "state_topic": f"{self.device_id}/playlist/mode/state",
  216. "options": ["single", "loop"],
  217. "device": base_device,
  218. "icon": "mdi:repeat",
  219. "entity_category": "config"
  220. }
  221. self._publish_discovery("select", "playlist_mode", playlist_mode_config)
  222. # Playlist Pause Time Number Input
  223. pause_time_config = {
  224. "name": f"{self.device_name} Playlist Pause Time",
  225. "unique_id": f"{self.device_id}_pause_time",
  226. "command_topic": f"{self.device_id}/playlist/pause_time/set",
  227. "state_topic": f"{self.device_id}/playlist/pause_time/state",
  228. "device": base_device,
  229. "icon": "mdi:timer",
  230. "entity_category": "config",
  231. "mode": "box",
  232. "unit_of_measurement": "seconds",
  233. "min": 0,
  234. "max": 86400,
  235. }
  236. self._publish_discovery("number", "pause_time", pause_time_config)
  237. # Clear Pattern Select
  238. clear_pattern_config = {
  239. "name": f"{self.device_name} Clear Pattern",
  240. "unique_id": f"{self.device_id}_clear_pattern",
  241. "command_topic": f"{self.device_id}/playlist/clear_pattern/set",
  242. "state_topic": f"{self.device_id}/playlist/clear_pattern/state",
  243. "options": ["none", "random", "adaptive", "clear_from_in", "clear_from_out", "clear_sideway"],
  244. "device": base_device,
  245. "icon": "mdi:eraser",
  246. "entity_category": "config"
  247. }
  248. self._publish_discovery("select", "clear_pattern", clear_pattern_config)
  249. # Shuffle Switch
  250. shuffle_config = {
  251. "name": f"{self.device_name} Shuffle",
  252. "unique_id": f"{self.device_id}_shuffle",
  253. "command_topic": f"{self.device_id}/playlist/shuffle/set",
  254. "state_topic": f"{self.device_id}/playlist/shuffle/state",
  255. "payload_on": "ON",
  256. "payload_off": "OFF",
  257. "device": base_device,
  258. "icon": "mdi:shuffle-variant",
  259. "entity_category": "config"
  260. }
  261. self._publish_discovery("switch", "shuffle", shuffle_config)
  262. # Completion Percentage Sensor
  263. completion_config = {
  264. "name": f"{self.device_name} Completion",
  265. "unique_id": f"{self.device_id}_completion",
  266. "state_topic": self.completion_topic,
  267. "device": base_device,
  268. "icon": "mdi:progress-clock",
  269. "unit_of_measurement": "%",
  270. "state_class": "measurement",
  271. "entity_category": "diagnostic"
  272. }
  273. self._publish_discovery("sensor", "completion", completion_config)
  274. # Time Remaining Sensor
  275. time_remaining_config = {
  276. "name": f"{self.device_name} Time Remaining",
  277. "unique_id": f"{self.device_id}_time_remaining",
  278. "state_topic": self.time_remaining_topic,
  279. "device": base_device,
  280. "icon": "mdi:timer-sand",
  281. "unit_of_measurement": "s",
  282. "device_class": "duration",
  283. "state_class": "measurement",
  284. "entity_category": "diagnostic"
  285. }
  286. self._publish_discovery("sensor", "time_remaining", time_remaining_config)
  287. # LED Control Entities (only for DW LEDs - WLED has its own MQTT integration)
  288. if state.led_provider == "dw_leds":
  289. # LED Power Switch
  290. led_power_config = {
  291. "name": f"{self.device_name} LED Power",
  292. "unique_id": f"{self.device_id}_led_power",
  293. "command_topic": self.led_power_topic,
  294. "state_topic": f"{self.device_id}/led/power/state",
  295. "payload_on": "ON",
  296. "payload_off": "OFF",
  297. "device": base_device,
  298. "icon": "mdi:lightbulb",
  299. "optimistic": False
  300. }
  301. self._publish_discovery("switch", "led_power", led_power_config)
  302. # LED Brightness Control
  303. led_brightness_config = {
  304. "name": f"{self.device_name} LED Brightness",
  305. "unique_id": f"{self.device_id}_led_brightness",
  306. "command_topic": self.led_brightness_topic,
  307. "state_topic": f"{self.device_id}/led/brightness/state",
  308. "device": base_device,
  309. "icon": "mdi:brightness-6",
  310. "min": 0,
  311. "max": 100,
  312. "mode": "slider"
  313. }
  314. self._publish_discovery("number", "led_brightness", led_brightness_config)
  315. # LED Effect Selector
  316. led_effect_options = [
  317. "Static", "Blink", "Breathe", "Wipe", "Fade", "Scan", "Dual Scan",
  318. "Rainbow Cycle", "Rainbow", "Theater Chase", "Running Lights",
  319. "Random Color", "Dynamic", "Twinkle", "Sparkle", "Strobe", "Fire",
  320. "Comet", "Chase", "Police", "Lightning", "Fireworks", "Ripple", "Flow",
  321. "Colorloop", "Palette Flow", "Gradient", "Multi Strobe", "Waves", "BPM",
  322. "Juggle", "Meteor", "Pride", "Pacifica", "Plasma", "Dissolve", "Glitter",
  323. "Confetti", "Sinelon", "Candle", "Aurora", "Rain", "Halloween", "Noise",
  324. "Funky Plank"
  325. ]
  326. led_effect_config = {
  327. "name": f"{self.device_name} LED Effect",
  328. "unique_id": f"{self.device_id}_led_effect",
  329. "command_topic": self.led_effect_topic,
  330. "state_topic": f"{self.device_id}/led/effect/state",
  331. "options": led_effect_options,
  332. "device": base_device,
  333. "icon": "mdi:palette"
  334. }
  335. self._publish_discovery("select", "led_effect", led_effect_config)
  336. # LED Speed Control
  337. led_speed_config = {
  338. "name": f"{self.device_name} LED Speed",
  339. "unique_id": f"{self.device_id}_led_speed",
  340. "command_topic": self.led_speed_topic,
  341. "state_topic": f"{self.device_id}/led/speed/state",
  342. "device": base_device,
  343. "icon": "mdi:speedometer",
  344. "min": 0,
  345. "max": 255,
  346. "mode": "slider"
  347. }
  348. self._publish_discovery("number", "led_speed", led_speed_config)
  349. # LED Intensity Control
  350. led_intensity_config = {
  351. "name": f"{self.device_name} LED Intensity",
  352. "unique_id": f"{self.device_id}_led_intensity",
  353. "command_topic": self.led_intensity_topic,
  354. "state_topic": f"{self.device_id}/led/intensity/state",
  355. "device": base_device,
  356. "icon": "mdi:brightness-7",
  357. "min": 0,
  358. "max": 255,
  359. "mode": "slider"
  360. }
  361. self._publish_discovery("number", "led_intensity", led_intensity_config)
  362. # LED RGB Color Control
  363. led_color_config = {
  364. "name": f"{self.device_name} LED Color",
  365. "unique_id": f"{self.device_id}_led_color",
  366. "command_topic": self.led_color_topic,
  367. "state_topic": f"{self.device_id}/led/color/state",
  368. "rgb_command_topic": self.led_color_topic,
  369. "rgb_state_topic": f"{self.device_id}/led/color/state",
  370. "device": base_device,
  371. "icon": "mdi:palette-swatch",
  372. "schema": "json",
  373. "rgb": True
  374. }
  375. self._publish_discovery("light", "led_color", led_color_config)
  376. # Screen Control Entities (only if screen controller is available)
  377. if state.screen_controller and state.screen_controller.available:
  378. screen_status = state.screen_controller.get_status()
  379. # Screen Power Switch
  380. screen_power_config = {
  381. "name": f"{self.device_name} Screen Power",
  382. "unique_id": f"{self.device_id}_screen_power",
  383. "command_topic": self.screen_power_topic,
  384. "state_topic": f"{self.device_id}/screen/power/state",
  385. "payload_on": "ON",
  386. "payload_off": "OFF",
  387. "device": base_device,
  388. "icon": "mdi:monitor",
  389. "optimistic": False
  390. }
  391. self._publish_discovery("switch", "screen_power", screen_power_config)
  392. # Screen Brightness Number
  393. screen_brightness_config = {
  394. "name": f"{self.device_name} Screen Brightness",
  395. "unique_id": f"{self.device_id}_screen_brightness",
  396. "command_topic": self.screen_brightness_topic,
  397. "state_topic": f"{self.device_id}/screen/brightness/state",
  398. "device": base_device,
  399. "icon": "mdi:brightness-6",
  400. "min": 0,
  401. "max": screen_status.get("max_brightness", 255),
  402. "mode": "slider"
  403. }
  404. self._publish_discovery("number", "screen_brightness", screen_brightness_config)
  405. def _publish_discovery(self, component: str, config_type: str, config: dict):
  406. """Helper method to publish HA discovery configs."""
  407. if not self.is_enabled:
  408. return
  409. discovery_topic = f"{self.discovery_prefix}/{component}/{self.device_id}/{config_type}/config"
  410. self.client.publish(discovery_topic, json.dumps(config), retain=True)
  411. def _publish_running_state(self, running_state=None):
  412. """Helper to publish running state and button availability."""
  413. if running_state is None:
  414. if not self.state.current_playing_file:
  415. running_state = "idle"
  416. elif self.state.pause_requested:
  417. running_state = "paused"
  418. else:
  419. running_state = "running"
  420. self.client.publish(self.running_state_topic, running_state, retain=True)
  421. # Update button availability based on state
  422. self.client.publish(f"{self.device_id}/command/pause/available",
  423. "true" if running_state == "running" else "false",
  424. retain=True)
  425. self.client.publish(f"{self.device_id}/command/play/available",
  426. "true" if running_state == "paused" else "false",
  427. retain=True)
  428. # Skip is available when running and a playlist is active
  429. self.client.publish(f"{self.device_id}/command/skip/available",
  430. "true" if running_state in ("running", "paused") and bool(self.state.current_playlist) else "false",
  431. retain=True)
  432. def _publish_pattern_state(self, current_file=None):
  433. """Helper to publish pattern state."""
  434. if current_file is None:
  435. current_file = self.state.current_playing_file
  436. if current_file:
  437. if current_file.startswith('./patterns/'):
  438. current_file = current_file[len('./patterns/'):]
  439. else:
  440. current_file = current_file.split("/")[-1].split("\\")[-1]
  441. self.client.publish(f"{self.pattern_select_topic}/state", current_file, retain=True)
  442. else:
  443. # Clear the pattern selection
  444. self.client.publish(f"{self.pattern_select_topic}/state", "None", retain=True)
  445. def _publish_playlist_state(self, playlist_name=None):
  446. """Helper to publish playlist state."""
  447. if playlist_name is None:
  448. playlist_name = self.state.current_playlist_name
  449. if playlist_name:
  450. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  451. else:
  452. # Clear the playlist selection
  453. self.client.publish(f"{self.playlist_select_topic}/state", "None", retain=True)
  454. def _publish_serial_state(self):
  455. """Helper to publish serial state."""
  456. serial_connected = (state.conn.is_connected() if state.conn else False)
  457. serial_port = state.port if serial_connected else None
  458. serial_status = f"connected to {serial_port}" if serial_connected else "disconnected"
  459. self.client.publish(self.serial_state_topic, serial_status, retain=True)
  460. def _publish_progress_state(self):
  461. """Helper to publish completion percentage and time remaining."""
  462. if state.execution_progress:
  463. current, total, remaining_time, elapsed_time = state.execution_progress
  464. completion_percentage = (current / total * 100) if total > 0 else 0
  465. # Publish completion percentage (rounded to 1 decimal place)
  466. self.client.publish(self.completion_topic, round(completion_percentage, 1), retain=True)
  467. # Publish time remaining (rounded to nearest second, defaulting to 0 if None)
  468. time_remaining_seconds = round(remaining_time) if remaining_time is not None else 0
  469. self.client.publish(self.time_remaining_topic, max(0, time_remaining_seconds), retain=True)
  470. else:
  471. # No pattern running, publish zeros
  472. self.client.publish(self.completion_topic, 0, retain=True)
  473. self.client.publish(self.time_remaining_topic, 0, retain=True)
  474. def _publish_playlist_settings_state(self):
  475. """Helper to publish playlist settings state (mode, pause_time, clear_pattern, shuffle)."""
  476. self.client.publish(f"{self.device_id}/playlist/mode/state", state.playlist_mode, retain=True)
  477. self.client.publish(f"{self.device_id}/playlist/pause_time/state", state.pause_time, retain=True)
  478. self.client.publish(f"{self.device_id}/playlist/clear_pattern/state", state.clear_pattern, retain=True)
  479. shuffle_state = "ON" if state.shuffle else "OFF"
  480. self.client.publish(f"{self.device_id}/playlist/shuffle/state", shuffle_state, retain=True)
  481. def _publish_led_state(self):
  482. """Helper to publish LED state to MQTT (DW LEDs only - WLED has its own MQTT)."""
  483. if not state.led_controller or state.led_provider != "dw_leds":
  484. return
  485. try:
  486. status = state.led_controller.check_status()
  487. if not status.get("connected", False):
  488. return
  489. # Publish power state (check both "power" for WLED compatibility and "power_on" for DW LEDs)
  490. is_powered = status.get("power_on", status.get("power", False))
  491. power_state = "ON" if is_powered else "OFF"
  492. self.client.publish(f"{self.device_id}/led/power/state", power_state, retain=True)
  493. # Publish brightness (convert from 0-1 to 0-100)
  494. if "brightness" in status:
  495. brightness = int(status["brightness"] * 100)
  496. self.client.publish(f"{self.device_id}/led/brightness/state", brightness, retain=True)
  497. # Publish effect
  498. if "effect_id" in status:
  499. effect_map = {
  500. 0: "Static", 1: "Blink", 2: "Breathe", 3: "Wipe", 4: "Fade",
  501. 5: "Scan", 6: "Dual Scan", 7: "Rainbow Cycle", 8: "Rainbow",
  502. 9: "Theater Chase", 10: "Running Lights", 11: "Random Color",
  503. 12: "Dynamic", 13: "Twinkle", 14: "Sparkle", 15: "Strobe",
  504. 16: "Fire", 17: "Comet", 18: "Chase", 19: "Police", 20: "Lightning",
  505. 21: "Fireworks", 22: "Ripple", 23: "Flow", 24: "Colorloop",
  506. 25: "Palette Flow", 26: "Gradient", 27: "Multi Strobe", 28: "Waves",
  507. 29: "BPM", 30: "Juggle", 31: "Meteor", 32: "Pride", 33: "Pacifica",
  508. 34: "Plasma", 35: "Dissolve", 36: "Glitter", 37: "Confetti",
  509. 38: "Sinelon", 39: "Candle", 40: "Aurora", 41: "Rain",
  510. 42: "Halloween", 43: "Noise", 44: "Funky Plank"
  511. }
  512. effect_name = effect_map.get(status["effect_id"], "Static")
  513. self.client.publish(f"{self.device_id}/led/effect/state", effect_name, retain=True)
  514. # Publish speed
  515. if "speed" in status:
  516. self.client.publish(f"{self.device_id}/led/speed/state", status["speed"], retain=True)
  517. # Publish intensity
  518. if "intensity" in status:
  519. self.client.publish(f"{self.device_id}/led/intensity/state", status["intensity"], retain=True)
  520. # Publish color (RGB)
  521. if "colors" in status and len(status["colors"]) > 0:
  522. # colors is array of hex strings like ["#ff0000", "#00ff00", "#0000ff"]
  523. # Convert first color to RGB dict
  524. color_hex = status["colors"][0]
  525. if color_hex and color_hex.startswith('#') and len(color_hex) == 7:
  526. r = int(color_hex[1:3], 16)
  527. g = int(color_hex[3:5], 16)
  528. b = int(color_hex[5:7], 16)
  529. self.client.publish(f"{self.device_id}/led/color/state",
  530. json.dumps({"r": r, "g": g, "b": b}), retain=True)
  531. except Exception as e:
  532. logger.error(f"Error publishing LED state: {e}")
  533. def _publish_screen_state(self):
  534. """Helper to publish screen (LCD backlight) state to MQTT."""
  535. if not state.screen_controller or not state.screen_controller.available:
  536. return
  537. try:
  538. status = state.screen_controller.get_status()
  539. power_state = "ON" if status["power_on"] else "OFF"
  540. self.client.publish(f"{self.device_id}/screen/power/state", power_state, retain=True)
  541. self.client.publish(f"{self.device_id}/screen/brightness/state", status["brightness"], retain=True)
  542. except Exception as e:
  543. logger.error(f"Error publishing screen state: {e}")
  544. def update_state(self, current_file=None, is_running=None, playlist=None, playlist_name=None):
  545. """Update state in Home Assistant. Only publishes the attributes that are explicitly passed."""
  546. if not self.is_enabled:
  547. return
  548. # Update pattern state if current_file is provided
  549. if current_file is not None:
  550. self._publish_pattern_state(current_file)
  551. # Update running state and button availability if is_running is provided
  552. if is_running is not None:
  553. running_state = "running" if is_running else "paused" if self.state.current_playing_file else "idle"
  554. self._publish_running_state(running_state)
  555. # Update playlist state if playlist info is provided
  556. if playlist_name is not None:
  557. self._publish_playlist_state(playlist_name)
  558. def on_connect(self, client, userdata, flags, rc):
  559. """Callback when connected to MQTT broker."""
  560. if rc == 0:
  561. self._connected = True
  562. logger.info("MQTT Connection Accepted.")
  563. # Subscribe to command topics
  564. client.subscribe([
  565. (self.command_topic, 0),
  566. (self.pattern_select_topic, 0),
  567. (self.playlist_select_topic, 0),
  568. (self.speed_topic, 0),
  569. (f"{self.device_id}/command/stop", 0),
  570. (f"{self.device_id}/command/pause", 0),
  571. (f"{self.device_id}/command/play", 0),
  572. (f"{self.device_id}/command/skip", 0),
  573. (f"{self.device_id}/playlist/mode/set", 0),
  574. (f"{self.device_id}/playlist/pause_time/set", 0),
  575. (f"{self.device_id}/playlist/clear_pattern/set", 0),
  576. (f"{self.device_id}/playlist/shuffle/set", 0),
  577. (self.led_power_topic, 0),
  578. (self.led_brightness_topic, 0),
  579. (self.led_effect_topic, 0),
  580. (self.led_speed_topic, 0),
  581. (self.led_intensity_topic, 0),
  582. (self.led_color_topic, 0),
  583. (self.screen_power_topic, 0),
  584. (self.screen_brightness_topic, 0),
  585. ])
  586. # Publish discovery configurations
  587. self.setup_ha_discovery()
  588. else:
  589. self._connected = False
  590. error_messages = {
  591. 1: "Protocol level not supported",
  592. 2: "The client-identifier is not allowed by the server",
  593. 3: "The MQTT service is not available",
  594. 4: "The data in the username or password is malformed",
  595. 5: "The client is not authorized to connect"
  596. }
  597. error_msg = error_messages.get(rc, f"Unknown error code: {rc}")
  598. logger.error(f"MQTT Connection Refused. {error_msg}")
  599. def on_disconnect(self, client, userdata, rc):
  600. """Callback when disconnected from MQTT broker."""
  601. self._connected = False
  602. if rc == 0:
  603. logger.info("MQTT disconnected cleanly")
  604. else:
  605. logger.warning(f"MQTT disconnected unexpectedly with code: {rc}")
  606. def on_message(self, client, userdata, msg):
  607. """Callback when message is received."""
  608. try:
  609. if msg.topic == self.pattern_select_topic:
  610. from modules.core.pattern_manager import THETA_RHO_DIR
  611. # Handle pattern selection
  612. pattern_name = msg.payload.decode()
  613. if pattern_name in self.patterns:
  614. # Schedule the coroutine to run in the main event loop
  615. asyncio.run_coroutine_threadsafe(
  616. self.callback_registry['run_pattern'](file_path=f"{THETA_RHO_DIR}/{pattern_name}"),
  617. self.main_loop
  618. ).add_done_callback(
  619. lambda _: self._publish_pattern_state(None) # Clear pattern after execution
  620. )
  621. self.client.publish(f"{self.pattern_select_topic}/state", pattern_name, retain=True)
  622. elif msg.topic == self.playlist_select_topic:
  623. # Handle playlist selection
  624. playlist_name = msg.payload.decode()
  625. if playlist_name in self.playlists:
  626. # Schedule the coroutine to run in the main event loop
  627. asyncio.run_coroutine_threadsafe(
  628. self.callback_registry['run_playlist'](
  629. playlist_name=playlist_name,
  630. run_mode=self.state.playlist_mode,
  631. pause_time=self.state.pause_time,
  632. clear_pattern=self.state.clear_pattern,
  633. shuffle=self.state.shuffle
  634. ),
  635. self.main_loop
  636. ).add_done_callback(
  637. lambda _: self._publish_playlist_state(None) # Clear playlist after execution
  638. )
  639. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  640. elif msg.topic == self.speed_topic:
  641. speed = int(msg.payload.decode())
  642. self.callback_registry['set_speed'](speed)
  643. elif msg.topic == f"{self.device_id}/command/stop":
  644. # Handle stop command
  645. callback = self.callback_registry['stop']
  646. if asyncio.iscoroutinefunction(callback):
  647. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  648. else:
  649. callback()
  650. # Clear both pattern and playlist selections
  651. self._publish_pattern_state(None)
  652. self._publish_playlist_state(None)
  653. elif msg.topic == f"{self.device_id}/command/pause":
  654. # Handle pause command - only if in running state
  655. if bool(self.state.current_playing_file) and not self.state.pause_requested:
  656. # Check if callback is async or sync
  657. callback = self.callback_registry['pause']
  658. if asyncio.iscoroutinefunction(callback):
  659. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  660. else:
  661. callback()
  662. elif msg.topic == f"{self.device_id}/command/play":
  663. # Handle play command - only if in paused state
  664. if bool(self.state.current_playing_file) and self.state.pause_requested:
  665. # Check if callback is async or sync
  666. callback = self.callback_registry['resume']
  667. if asyncio.iscoroutinefunction(callback):
  668. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  669. else:
  670. callback()
  671. elif msg.topic == f"{self.device_id}/command/skip":
  672. # Handle skip command - only if a playlist is running
  673. if self.state.current_playlist:
  674. callback = self.callback_registry['skip']
  675. if asyncio.iscoroutinefunction(callback):
  676. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  677. else:
  678. callback()
  679. elif msg.topic == f"{self.device_id}/playlist/mode/set":
  680. mode = msg.payload.decode()
  681. if mode in ["single", "loop"]:
  682. state.playlist_mode = mode
  683. self.client.publish(f"{self.device_id}/playlist/mode/state", mode, retain=True)
  684. elif msg.topic == f"{self.device_id}/playlist/pause_time/set":
  685. pause_time = float(msg.payload.decode())
  686. if 0 <= pause_time <= 60:
  687. state.pause_time = pause_time
  688. self.client.publish(f"{self.device_id}/playlist/pause_time/state", pause_time, retain=True)
  689. elif msg.topic == f"{self.device_id}/playlist/clear_pattern/set":
  690. clear_pattern = msg.payload.decode()
  691. if clear_pattern in ["none", "random", "adaptive", "clear_from_in", "clear_from_out", "clear_sideway"]:
  692. state.clear_pattern = clear_pattern
  693. self.client.publish(f"{self.device_id}/playlist/clear_pattern/state", clear_pattern, retain=True)
  694. elif msg.topic == f"{self.device_id}/playlist/shuffle/set":
  695. payload = msg.payload.decode()
  696. shuffle_value = payload == "ON"
  697. state.shuffle = shuffle_value
  698. self.client.publish(f"{self.device_id}/playlist/shuffle/state", payload, retain=True)
  699. elif msg.topic == self.led_power_topic:
  700. # Handle LED power command (DW LEDs only)
  701. payload = msg.payload.decode()
  702. if state.led_controller and state.led_provider == "dw_leds":
  703. power_state = 1 if payload == "ON" else 0
  704. state.led_controller.set_power(power_state)
  705. # Reset idle timeout when LEDs are manually powered on via MQTT (only if idle timeout is enabled)
  706. if payload == "ON" and state.dw_led_idle_timeout_enabled:
  707. state.dw_led_last_activity_time = time.time()
  708. logger.debug("LED activity time reset due to MQTT power on")
  709. self.client.publish(f"{self.device_id}/led/power/state", payload, retain=True)
  710. elif msg.topic == self.led_brightness_topic:
  711. # Handle LED brightness command (DW LEDs only)
  712. brightness = int(msg.payload.decode())
  713. if 0 <= brightness <= 100 and state.led_controller and state.led_provider == "dw_leds":
  714. controller = state.led_controller.get_controller()
  715. if controller and hasattr(controller, 'set_brightness'):
  716. # DW LED controller expects 0-100, converts internally to 0.0-1.0
  717. controller.set_brightness(brightness)
  718. self.client.publish(f"{self.device_id}/led/brightness/state", brightness, retain=True)
  719. elif msg.topic == self.led_effect_topic:
  720. # Handle LED effect command (DW LEDs only)
  721. effect_name = msg.payload.decode()
  722. if state.led_controller and state.led_provider == "dw_leds":
  723. # Map effect name to ID
  724. effect_map = {
  725. "Static": 0, "Blink": 1, "Breathe": 2, "Wipe": 3, "Fade": 4,
  726. "Scan": 5, "Dual Scan": 6, "Rainbow Cycle": 7, "Rainbow": 8,
  727. "Theater Chase": 9, "Running Lights": 10, "Random Color": 11,
  728. "Dynamic": 12, "Twinkle": 13, "Sparkle": 14, "Strobe": 15,
  729. "Fire": 16, "Comet": 17, "Chase": 18, "Police": 19, "Lightning": 20,
  730. "Fireworks": 21, "Ripple": 22, "Flow": 23, "Colorloop": 24,
  731. "Palette Flow": 25, "Gradient": 26, "Multi Strobe": 27, "Waves": 28,
  732. "BPM": 29, "Juggle": 30, "Meteor": 31, "Pride": 32, "Pacifica": 33,
  733. "Plasma": 34, "Dissolve": 35, "Glitter": 36, "Confetti": 37,
  734. "Sinelon": 38, "Candle": 39, "Aurora": 40, "Rain": 41,
  735. "Halloween": 42, "Noise": 43, "Funky Plank": 44
  736. }
  737. effect_id = effect_map.get(effect_name)
  738. if effect_id is not None:
  739. controller = state.led_controller.get_controller()
  740. if controller and hasattr(controller, 'set_effect'):
  741. controller.set_effect(effect_id)
  742. self.client.publish(f"{self.device_id}/led/effect/state", effect_name, retain=True)
  743. elif msg.topic == self.led_speed_topic:
  744. # Handle LED speed command (DW LEDs only)
  745. speed = int(msg.payload.decode())
  746. if 0 <= speed <= 255 and state.led_controller and state.led_provider == "dw_leds":
  747. controller = state.led_controller.get_controller()
  748. if controller and hasattr(controller, 'set_speed'):
  749. controller.set_speed(speed)
  750. self.client.publish(f"{self.device_id}/led/speed/state", speed, retain=True)
  751. elif msg.topic == self.led_intensity_topic:
  752. # Handle LED intensity command (DW LEDs only)
  753. intensity = int(msg.payload.decode())
  754. if 0 <= intensity <= 255 and state.led_controller and state.led_provider == "dw_leds":
  755. controller = state.led_controller.get_controller()
  756. if controller and hasattr(controller, 'set_intensity'):
  757. controller.set_intensity(intensity)
  758. self.client.publish(f"{self.device_id}/led/intensity/state", intensity, retain=True)
  759. elif msg.topic == self.led_color_topic:
  760. # Handle LED color command (RGB) (DW LEDs only)
  761. try:
  762. color_data = json.loads(msg.payload.decode())
  763. if state.led_controller and state.led_provider == "dw_leds" and 'r' in color_data and 'g' in color_data and 'b' in color_data:
  764. controller = state.led_controller.get_controller()
  765. if controller and hasattr(controller, 'set_color'):
  766. r, g, b = color_data['r'], color_data['g'], color_data['b']
  767. controller.set_color(r, g, b)
  768. self.client.publish(f"{self.device_id}/led/color/state",
  769. json.dumps({"r": r, "g": g, "b": b}), retain=True)
  770. except json.JSONDecodeError:
  771. logger.error(f"Invalid JSON for color command: {msg.payload}")
  772. elif msg.topic == self.screen_power_topic:
  773. # Handle screen power command
  774. payload = msg.payload.decode()
  775. if state.screen_controller and state.screen_controller.available:
  776. state.screen_controller.set_power(payload == "ON")
  777. self._publish_screen_state()
  778. elif msg.topic == self.screen_brightness_topic:
  779. # Handle screen brightness command
  780. brightness = int(msg.payload.decode())
  781. if state.screen_controller and state.screen_controller.available:
  782. state.screen_controller.set_brightness(brightness)
  783. self._publish_screen_state()
  784. else:
  785. # Handle other commands
  786. payload = json.loads(msg.payload.decode())
  787. command = payload.get('command')
  788. params = payload.get('params', {})
  789. if command in self.callback_registry:
  790. self.callback_registry[command](**params)
  791. else:
  792. logger.error(f"Unknown command received: {command}")
  793. except json.JSONDecodeError:
  794. logger.error(f"Invalid JSON payload received: {msg.payload}")
  795. except Exception as e:
  796. logger.error(f"Error processing MQTT message: {e}")
  797. def publish_status(self):
  798. """Publish status updates periodically."""
  799. while self.running:
  800. try:
  801. # Update all states
  802. self._publish_running_state()
  803. self._publish_pattern_state()
  804. self._publish_playlist_state()
  805. self._publish_serial_state()
  806. self._publish_progress_state()
  807. # Update speed state
  808. self.client.publish(f"{self.speed_topic}/state", self.state.speed, retain=True)
  809. # Update LED state
  810. self._publish_led_state()
  811. # Update screen state
  812. self._publish_screen_state()
  813. # Publish keepalive status
  814. status = {
  815. "timestamp": time.time(),
  816. "client_id": self.client_id
  817. }
  818. self.client.publish(self.status_topic, json.dumps(status))
  819. # Wait for next interval
  820. time.sleep(self.status_interval)
  821. except Exception as e:
  822. logger.error(f"Error publishing status: {e}")
  823. time.sleep(5) # Wait before retry
  824. def start(self) -> None:
  825. """Start the MQTT handler."""
  826. if not self.is_enabled:
  827. return
  828. try:
  829. self.client.connect(self.broker, self.port)
  830. self.client.loop_start()
  831. # Start status publishing thread
  832. self.running = True
  833. self.status_thread = threading.Thread(target=self.publish_status, daemon=True)
  834. self.status_thread.start()
  835. # Get initial pattern and playlist lists
  836. self.patterns = list_theta_rho_files()
  837. self.playlists = list_all_playlists()
  838. # Wait a bit for MQTT connection to establish
  839. time.sleep(1)
  840. # Publish initial states
  841. self._publish_running_state()
  842. self._publish_pattern_state()
  843. self._publish_playlist_state()
  844. self._publish_serial_state()
  845. self._publish_progress_state()
  846. self._publish_playlist_settings_state()
  847. self._publish_led_state()
  848. self._publish_screen_state()
  849. # Setup Home Assistant discovery
  850. self.setup_ha_discovery()
  851. logger.info("MQTT Handler started successfully")
  852. except Exception as e:
  853. logger.error(f"Failed to start MQTT Handler: {e}")
  854. def stop(self) -> None:
  855. """Stop the MQTT handler."""
  856. if not self.is_enabled:
  857. return
  858. # First stop the running flag to prevent new iterations
  859. self.running = False
  860. # Clean up status thread
  861. local_status_thread = self.status_thread # Keep a local reference
  862. if local_status_thread and local_status_thread.is_alive():
  863. try:
  864. local_status_thread.join(timeout=5)
  865. if local_status_thread.is_alive():
  866. logger.warning("MQTT status thread did not terminate cleanly")
  867. except Exception as e:
  868. logger.error(f"Error joining status thread: {e}")
  869. self.status_thread = None
  870. # Clean up MQTT client
  871. try:
  872. if hasattr(self, 'client'):
  873. self.client.loop_stop()
  874. self.client.disconnect()
  875. except Exception as e:
  876. logger.error(f"Error disconnecting MQTT client: {e}")
  877. # Clean up main loop reference
  878. self.main_loop = None
  879. logger.info("MQTT handler stopped")
  880. @property
  881. def is_enabled(self) -> bool:
  882. """Return whether MQTT functionality is enabled.
  883. MQTT is enabled if:
  884. 1. A broker address is configured (either via state or env var), AND
  885. 2. Either state.mqtt_enabled is True, OR no UI config exists (env-only mode)
  886. """
  887. # If no broker configured, MQTT is disabled
  888. if not self.broker:
  889. return False
  890. # If state has mqtt_enabled explicitly set (UI was used), respect that setting
  891. # If mqtt_broker is set in state, user configured via UI - use mqtt_enabled
  892. if state.mqtt_broker:
  893. return state.mqtt_enabled
  894. # Otherwise, broker came from env vars - enable if broker exists
  895. return True
  896. @property
  897. def is_connected(self) -> bool:
  898. """Return whether MQTT client is currently connected to the broker."""
  899. return self._connected and self.is_enabled