handler.py 43 KB

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