1
0

handler.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. # Completion Percentage Sensor
  223. completion_config = {
  224. "name": f"{self.device_name} Completion",
  225. "unique_id": f"{self.device_id}_completion",
  226. "state_topic": self.completion_topic,
  227. "device": base_device,
  228. "icon": "mdi:progress-clock",
  229. "unit_of_measurement": "%",
  230. "state_class": "measurement",
  231. "entity_category": "diagnostic"
  232. }
  233. self._publish_discovery("sensor", "completion", completion_config)
  234. # Time Remaining Sensor
  235. time_remaining_config = {
  236. "name": f"{self.device_name} Time Remaining",
  237. "unique_id": f"{self.device_id}_time_remaining",
  238. "state_topic": self.time_remaining_topic,
  239. "device": base_device,
  240. "icon": "mdi:timer-sand",
  241. "unit_of_measurement": "s",
  242. "device_class": "duration",
  243. "state_class": "measurement",
  244. "entity_category": "diagnostic"
  245. }
  246. self._publish_discovery("sensor", "time_remaining", time_remaining_config)
  247. # LED Control Entities (only for DW LEDs - WLED has its own MQTT integration)
  248. if state.led_provider == "dw_leds":
  249. # LED Power Switch
  250. led_power_config = {
  251. "name": f"{self.device_name} LED Power",
  252. "unique_id": f"{self.device_id}_led_power",
  253. "command_topic": self.led_power_topic,
  254. "state_topic": f"{self.device_id}/led/power/state",
  255. "payload_on": "ON",
  256. "payload_off": "OFF",
  257. "device": base_device,
  258. "icon": "mdi:lightbulb",
  259. "optimistic": False
  260. }
  261. self._publish_discovery("switch", "led_power", led_power_config)
  262. # LED Brightness Control
  263. led_brightness_config = {
  264. "name": f"{self.device_name} LED Brightness",
  265. "unique_id": f"{self.device_id}_led_brightness",
  266. "command_topic": self.led_brightness_topic,
  267. "state_topic": f"{self.device_id}/led/brightness/state",
  268. "device": base_device,
  269. "icon": "mdi:brightness-6",
  270. "min": 0,
  271. "max": 100,
  272. "mode": "slider"
  273. }
  274. self._publish_discovery("number", "led_brightness", led_brightness_config)
  275. # LED Effect Selector
  276. led_effect_options = [
  277. "Static", "Blink", "Breathe", "Wipe", "Fade", "Scan", "Dual Scan",
  278. "Rainbow Cycle", "Rainbow", "Theater Chase", "Running Lights",
  279. "Random Color", "Dynamic", "Twinkle", "Sparkle", "Strobe", "Fire",
  280. "Comet", "Chase", "Police", "Lightning", "Fireworks", "Ripple", "Flow",
  281. "Colorloop", "Palette Flow", "Gradient", "Multi Strobe", "Waves", "BPM",
  282. "Juggle", "Meteor", "Pride", "Pacifica", "Plasma", "Dissolve", "Glitter",
  283. "Confetti", "Sinelon", "Candle", "Aurora", "Rain", "Halloween", "Noise",
  284. "Funky Plank"
  285. ]
  286. led_effect_config = {
  287. "name": f"{self.device_name} LED Effect",
  288. "unique_id": f"{self.device_id}_led_effect",
  289. "command_topic": self.led_effect_topic,
  290. "state_topic": f"{self.device_id}/led/effect/state",
  291. "options": led_effect_options,
  292. "device": base_device,
  293. "icon": "mdi:palette"
  294. }
  295. self._publish_discovery("select", "led_effect", led_effect_config)
  296. # LED Speed Control
  297. led_speed_config = {
  298. "name": f"{self.device_name} LED Speed",
  299. "unique_id": f"{self.device_id}_led_speed",
  300. "command_topic": self.led_speed_topic,
  301. "state_topic": f"{self.device_id}/led/speed/state",
  302. "device": base_device,
  303. "icon": "mdi:speedometer",
  304. "min": 0,
  305. "max": 255,
  306. "mode": "slider"
  307. }
  308. self._publish_discovery("number", "led_speed", led_speed_config)
  309. # LED Intensity Control
  310. led_intensity_config = {
  311. "name": f"{self.device_name} LED Intensity",
  312. "unique_id": f"{self.device_id}_led_intensity",
  313. "command_topic": self.led_intensity_topic,
  314. "state_topic": f"{self.device_id}/led/intensity/state",
  315. "device": base_device,
  316. "icon": "mdi:brightness-7",
  317. "min": 0,
  318. "max": 255,
  319. "mode": "slider"
  320. }
  321. self._publish_discovery("number", "led_intensity", led_intensity_config)
  322. # LED RGB Color Control
  323. led_color_config = {
  324. "name": f"{self.device_name} LED Color",
  325. "unique_id": f"{self.device_id}_led_color",
  326. "command_topic": self.led_color_topic,
  327. "state_topic": f"{self.device_id}/led/color/state",
  328. "rgb_command_topic": self.led_color_topic,
  329. "rgb_state_topic": f"{self.device_id}/led/color/state",
  330. "device": base_device,
  331. "icon": "mdi:palette-swatch",
  332. "schema": "json",
  333. "rgb": True
  334. }
  335. self._publish_discovery("light", "led_color", led_color_config)
  336. def _publish_discovery(self, component: str, config_type: str, config: dict):
  337. """Helper method to publish HA discovery configs."""
  338. if not self.is_enabled:
  339. return
  340. discovery_topic = f"{self.discovery_prefix}/{component}/{self.device_id}/{config_type}/config"
  341. self.client.publish(discovery_topic, json.dumps(config), retain=True)
  342. def _publish_running_state(self, running_state=None):
  343. """Helper to publish running state and button availability."""
  344. if running_state is None:
  345. if not self.state.current_playing_file:
  346. running_state = "idle"
  347. elif self.state.pause_requested:
  348. running_state = "paused"
  349. else:
  350. running_state = "running"
  351. self.client.publish(self.running_state_topic, running_state, retain=True)
  352. # Update button availability based on state
  353. self.client.publish(f"{self.device_id}/command/pause/available",
  354. "true" if running_state == "running" else "false",
  355. retain=True)
  356. self.client.publish(f"{self.device_id}/command/play/available",
  357. "true" if running_state == "paused" else "false",
  358. retain=True)
  359. def _publish_pattern_state(self, current_file=None):
  360. """Helper to publish pattern state."""
  361. if current_file is None:
  362. current_file = self.state.current_playing_file
  363. if current_file:
  364. if current_file.startswith('./patterns/'):
  365. current_file = current_file[len('./patterns/'):]
  366. else:
  367. current_file = current_file.split("/")[-1].split("\\")[-1]
  368. self.client.publish(f"{self.pattern_select_topic}/state", current_file, retain=True)
  369. else:
  370. # Clear the pattern selection
  371. self.client.publish(f"{self.pattern_select_topic}/state", "None", retain=True)
  372. def _publish_playlist_state(self, playlist_name=None):
  373. """Helper to publish playlist state."""
  374. if playlist_name is None:
  375. playlist_name = self.state.current_playlist_name
  376. if playlist_name:
  377. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  378. else:
  379. # Clear the playlist selection
  380. self.client.publish(f"{self.playlist_select_topic}/state", "None", retain=True)
  381. def _publish_serial_state(self):
  382. """Helper to publish serial state."""
  383. serial_connected = (state.conn.is_connected() if state.conn else False)
  384. serial_port = state.port if serial_connected else None
  385. serial_status = f"connected to {serial_port}" if serial_connected else "disconnected"
  386. self.client.publish(self.serial_state_topic, serial_status, retain=True)
  387. def _publish_progress_state(self):
  388. """Helper to publish completion percentage and time remaining."""
  389. if state.execution_progress:
  390. current, total, remaining_time, elapsed_time = state.execution_progress
  391. completion_percentage = (current / total * 100) if total > 0 else 0
  392. # Publish completion percentage (rounded to 1 decimal place)
  393. self.client.publish(self.completion_topic, round(completion_percentage, 1), retain=True)
  394. # Publish time remaining (rounded to nearest second, defaulting to 0 if None)
  395. time_remaining_seconds = round(remaining_time) if remaining_time is not None else 0
  396. self.client.publish(self.time_remaining_topic, max(0, time_remaining_seconds), retain=True)
  397. else:
  398. # No pattern running, publish zeros
  399. self.client.publish(self.completion_topic, 0, retain=True)
  400. self.client.publish(self.time_remaining_topic, 0, retain=True)
  401. def _publish_led_state(self):
  402. """Helper to publish LED state to MQTT (DW LEDs only - WLED has its own MQTT)."""
  403. if not state.led_controller or state.led_provider != "dw_leds":
  404. return
  405. try:
  406. status = state.led_controller.check_status()
  407. if not status.get("connected", False):
  408. return
  409. # Publish power state (check both "power" for WLED compatibility and "power_on" for DW LEDs)
  410. is_powered = status.get("power_on", status.get("power", False))
  411. power_state = "ON" if is_powered else "OFF"
  412. self.client.publish(f"{self.device_id}/led/power/state", power_state, retain=True)
  413. # Publish brightness (convert from 0-1 to 0-100)
  414. if "brightness" in status:
  415. brightness = int(status["brightness"] * 100)
  416. self.client.publish(f"{self.device_id}/led/brightness/state", brightness, retain=True)
  417. # Publish effect
  418. if "effect_id" in status:
  419. effect_map = {
  420. 0: "Static", 1: "Blink", 2: "Breathe", 3: "Wipe", 4: "Fade",
  421. 5: "Scan", 6: "Dual Scan", 7: "Rainbow Cycle", 8: "Rainbow",
  422. 9: "Theater Chase", 10: "Running Lights", 11: "Random Color",
  423. 12: "Dynamic", 13: "Twinkle", 14: "Sparkle", 15: "Strobe",
  424. 16: "Fire", 17: "Comet", 18: "Chase", 19: "Police", 20: "Lightning",
  425. 21: "Fireworks", 22: "Ripple", 23: "Flow", 24: "Colorloop",
  426. 25: "Palette Flow", 26: "Gradient", 27: "Multi Strobe", 28: "Waves",
  427. 29: "BPM", 30: "Juggle", 31: "Meteor", 32: "Pride", 33: "Pacifica",
  428. 34: "Plasma", 35: "Dissolve", 36: "Glitter", 37: "Confetti",
  429. 38: "Sinelon", 39: "Candle", 40: "Aurora", 41: "Rain",
  430. 42: "Halloween", 43: "Noise", 44: "Funky Plank"
  431. }
  432. effect_name = effect_map.get(status["effect_id"], "Static")
  433. self.client.publish(f"{self.device_id}/led/effect/state", effect_name, retain=True)
  434. # Publish speed
  435. if "speed" in status:
  436. self.client.publish(f"{self.device_id}/led/speed/state", status["speed"], retain=True)
  437. # Publish intensity
  438. if "intensity" in status:
  439. self.client.publish(f"{self.device_id}/led/intensity/state", status["intensity"], retain=True)
  440. # Publish color (RGB)
  441. if "colors" in status and len(status["colors"]) > 0:
  442. # colors is array of hex strings like ["#ff0000", "#00ff00", "#0000ff"]
  443. # Convert first color to RGB dict
  444. color_hex = status["colors"][0]
  445. if color_hex and color_hex.startswith('#') and len(color_hex) == 7:
  446. r = int(color_hex[1:3], 16)
  447. g = int(color_hex[3:5], 16)
  448. b = int(color_hex[5:7], 16)
  449. self.client.publish(f"{self.device_id}/led/color/state",
  450. json.dumps({"r": r, "g": g, "b": b}), retain=True)
  451. except Exception as e:
  452. logger.error(f"Error publishing LED state: {e}")
  453. def update_state(self, current_file=None, is_running=None, playlist=None, playlist_name=None):
  454. """Update state in Home Assistant. Only publishes the attributes that are explicitly passed."""
  455. if not self.is_enabled:
  456. return
  457. # Update pattern state if current_file is provided
  458. if current_file is not None:
  459. self._publish_pattern_state(current_file)
  460. # Update running state and button availability if is_running is provided
  461. if is_running is not None:
  462. running_state = "running" if is_running else "paused" if self.state.current_playing_file else "idle"
  463. self._publish_running_state(running_state)
  464. # Update playlist state if playlist info is provided
  465. if playlist_name is not None:
  466. self._publish_playlist_state(playlist_name)
  467. def on_connect(self, client, userdata, flags, rc):
  468. """Callback when connected to MQTT broker."""
  469. if rc == 0:
  470. self._connected = True
  471. logger.info("MQTT Connection Accepted.")
  472. # Subscribe to command topics
  473. client.subscribe([
  474. (self.command_topic, 0),
  475. (self.pattern_select_topic, 0),
  476. (self.playlist_select_topic, 0),
  477. (self.speed_topic, 0),
  478. (f"{self.device_id}/command/stop", 0),
  479. (f"{self.device_id}/command/pause", 0),
  480. (f"{self.device_id}/command/play", 0),
  481. (f"{self.device_id}/playlist/mode/set", 0),
  482. (f"{self.device_id}/playlist/pause_time/set", 0),
  483. (f"{self.device_id}/playlist/clear_pattern/set", 0),
  484. (self.led_power_topic, 0),
  485. (self.led_brightness_topic, 0),
  486. (self.led_effect_topic, 0),
  487. (self.led_speed_topic, 0),
  488. (self.led_intensity_topic, 0),
  489. (self.led_color_topic, 0),
  490. ])
  491. # Publish discovery configurations
  492. self.setup_ha_discovery()
  493. else:
  494. self._connected = False
  495. error_messages = {
  496. 1: "Protocol level not supported",
  497. 2: "The client-identifier is not allowed by the server",
  498. 3: "The MQTT service is not available",
  499. 4: "The data in the username or password is malformed",
  500. 5: "The client is not authorized to connect"
  501. }
  502. error_msg = error_messages.get(rc, f"Unknown error code: {rc}")
  503. logger.error(f"MQTT Connection Refused. {error_msg}")
  504. def on_disconnect(self, client, userdata, rc):
  505. """Callback when disconnected from MQTT broker."""
  506. self._connected = False
  507. if rc == 0:
  508. logger.info("MQTT disconnected cleanly")
  509. else:
  510. logger.warning(f"MQTT disconnected unexpectedly with code: {rc}")
  511. def on_message(self, client, userdata, msg):
  512. """Callback when message is received."""
  513. try:
  514. if msg.topic == self.pattern_select_topic:
  515. from modules.core.pattern_manager import THETA_RHO_DIR
  516. # Handle pattern selection
  517. pattern_name = msg.payload.decode()
  518. if pattern_name in self.patterns:
  519. # Schedule the coroutine to run in the main event loop
  520. asyncio.run_coroutine_threadsafe(
  521. self.callback_registry['run_pattern'](file_path=f"{THETA_RHO_DIR}/{pattern_name}"),
  522. self.main_loop
  523. ).add_done_callback(
  524. lambda _: self._publish_pattern_state(None) # Clear pattern after execution
  525. )
  526. self.client.publish(f"{self.pattern_select_topic}/state", pattern_name, retain=True)
  527. elif msg.topic == self.playlist_select_topic:
  528. # Handle playlist selection
  529. playlist_name = msg.payload.decode()
  530. if playlist_name in self.playlists:
  531. # Schedule the coroutine to run in the main event loop
  532. asyncio.run_coroutine_threadsafe(
  533. self.callback_registry['run_playlist'](
  534. playlist_name=playlist_name,
  535. run_mode=self.state.playlist_mode,
  536. pause_time=self.state.pause_time,
  537. clear_pattern=self.state.clear_pattern
  538. ),
  539. self.main_loop
  540. ).add_done_callback(
  541. lambda _: self._publish_playlist_state(None) # Clear playlist after execution
  542. )
  543. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  544. elif msg.topic == self.speed_topic:
  545. speed = int(msg.payload.decode())
  546. self.callback_registry['set_speed'](speed)
  547. elif msg.topic == f"{self.device_id}/command/stop":
  548. # Handle stop command
  549. callback = self.callback_registry['stop']
  550. if asyncio.iscoroutinefunction(callback):
  551. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  552. else:
  553. callback()
  554. # Clear both pattern and playlist selections
  555. self._publish_pattern_state(None)
  556. self._publish_playlist_state(None)
  557. elif msg.topic == f"{self.device_id}/command/pause":
  558. # Handle pause command - only if in running state
  559. if bool(self.state.current_playing_file) and not self.state.pause_requested:
  560. # Check if callback is async or sync
  561. callback = self.callback_registry['pause']
  562. if asyncio.iscoroutinefunction(callback):
  563. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  564. else:
  565. callback()
  566. elif msg.topic == f"{self.device_id}/command/play":
  567. # Handle play command - only if in paused state
  568. if bool(self.state.current_playing_file) and self.state.pause_requested:
  569. # Check if callback is async or sync
  570. callback = self.callback_registry['resume']
  571. if asyncio.iscoroutinefunction(callback):
  572. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  573. else:
  574. callback()
  575. elif msg.topic == f"{self.device_id}/playlist/mode/set":
  576. mode = msg.payload.decode()
  577. if mode in ["single", "loop"]:
  578. state.playlist_mode = mode
  579. self.client.publish(f"{self.device_id}/playlist/mode/state", mode, retain=True)
  580. elif msg.topic == f"{self.device_id}/playlist/pause_time/set":
  581. pause_time = float(msg.payload.decode())
  582. if 0 <= pause_time <= 60:
  583. state.pause_time = pause_time
  584. self.client.publish(f"{self.device_id}/playlist/pause_time/state", pause_time, retain=True)
  585. elif msg.topic == f"{self.device_id}/playlist/clear_pattern/set":
  586. clear_pattern = msg.payload.decode()
  587. if clear_pattern in ["none", "random", "adaptive", "clear_from_in", "clear_from_out", "clear_sideway"]:
  588. state.clear_pattern = clear_pattern
  589. self.client.publish(f"{self.device_id}/playlist/clear_pattern/state", clear_pattern, retain=True)
  590. elif msg.topic == self.led_power_topic:
  591. # Handle LED power command (DW LEDs only)
  592. payload = msg.payload.decode()
  593. if state.led_controller and state.led_provider == "dw_leds":
  594. power_state = 1 if payload == "ON" else 0
  595. state.led_controller.set_power(power_state)
  596. # Reset idle timeout when LEDs are manually powered on via MQTT (only if idle timeout is enabled)
  597. if payload == "ON" and state.dw_led_idle_timeout_enabled:
  598. state.dw_led_last_activity_time = time.time()
  599. logger.debug("LED activity time reset due to MQTT power on")
  600. self.client.publish(f"{self.device_id}/led/power/state", payload, retain=True)
  601. elif msg.topic == self.led_brightness_topic:
  602. # Handle LED brightness command (DW LEDs only)
  603. brightness = int(msg.payload.decode())
  604. if 0 <= brightness <= 100 and state.led_controller and state.led_provider == "dw_leds":
  605. controller = state.led_controller.get_controller()
  606. if controller and hasattr(controller, 'set_brightness'):
  607. controller.set_brightness(brightness / 100.0)
  608. self.client.publish(f"{self.device_id}/led/brightness/state", brightness, retain=True)
  609. elif msg.topic == self.led_effect_topic:
  610. # Handle LED effect command (DW LEDs only)
  611. effect_name = msg.payload.decode()
  612. if state.led_controller and state.led_provider == "dw_leds":
  613. # Map effect name to ID
  614. effect_map = {
  615. "Static": 0, "Blink": 1, "Breathe": 2, "Wipe": 3, "Fade": 4,
  616. "Scan": 5, "Dual Scan": 6, "Rainbow Cycle": 7, "Rainbow": 8,
  617. "Theater Chase": 9, "Running Lights": 10, "Random Color": 11,
  618. "Dynamic": 12, "Twinkle": 13, "Sparkle": 14, "Strobe": 15,
  619. "Fire": 16, "Comet": 17, "Chase": 18, "Police": 19, "Lightning": 20,
  620. "Fireworks": 21, "Ripple": 22, "Flow": 23, "Colorloop": 24,
  621. "Palette Flow": 25, "Gradient": 26, "Multi Strobe": 27, "Waves": 28,
  622. "BPM": 29, "Juggle": 30, "Meteor": 31, "Pride": 32, "Pacifica": 33,
  623. "Plasma": 34, "Dissolve": 35, "Glitter": 36, "Confetti": 37,
  624. "Sinelon": 38, "Candle": 39, "Aurora": 40, "Rain": 41,
  625. "Halloween": 42, "Noise": 43, "Funky Plank": 44
  626. }
  627. effect_id = effect_map.get(effect_name)
  628. if effect_id is not None:
  629. controller = state.led_controller.get_controller()
  630. if controller and hasattr(controller, 'set_effect'):
  631. controller.set_effect(effect_id)
  632. self.client.publish(f"{self.device_id}/led/effect/state", effect_name, retain=True)
  633. elif msg.topic == self.led_speed_topic:
  634. # Handle LED speed command (DW LEDs only)
  635. speed = int(msg.payload.decode())
  636. if 0 <= speed <= 255 and state.led_controller and state.led_provider == "dw_leds":
  637. controller = state.led_controller.get_controller()
  638. if controller and hasattr(controller, 'set_speed'):
  639. controller.set_speed(speed)
  640. self.client.publish(f"{self.device_id}/led/speed/state", speed, retain=True)
  641. elif msg.topic == self.led_intensity_topic:
  642. # Handle LED intensity command (DW LEDs only)
  643. intensity = int(msg.payload.decode())
  644. if 0 <= intensity <= 255 and state.led_controller and state.led_provider == "dw_leds":
  645. controller = state.led_controller.get_controller()
  646. if controller and hasattr(controller, 'set_intensity'):
  647. controller.set_intensity(intensity)
  648. self.client.publish(f"{self.device_id}/led/intensity/state", intensity, retain=True)
  649. elif msg.topic == self.led_color_topic:
  650. # Handle LED color command (RGB) (DW LEDs only)
  651. try:
  652. color_data = json.loads(msg.payload.decode())
  653. 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:
  654. controller = state.led_controller.get_controller()
  655. if controller and hasattr(controller, 'set_color'):
  656. r, g, b = color_data['r'], color_data['g'], color_data['b']
  657. controller.set_color(r, g, b)
  658. self.client.publish(f"{self.device_id}/led/color/state",
  659. json.dumps({"r": r, "g": g, "b": b}), retain=True)
  660. except json.JSONDecodeError:
  661. logger.error(f"Invalid JSON for color command: {msg.payload}")
  662. else:
  663. # Handle other commands
  664. payload = json.loads(msg.payload.decode())
  665. command = payload.get('command')
  666. params = payload.get('params', {})
  667. if command in self.callback_registry:
  668. self.callback_registry[command](**params)
  669. else:
  670. logger.error(f"Unknown command received: {command}")
  671. except json.JSONDecodeError:
  672. logger.error(f"Invalid JSON payload received: {msg.payload}")
  673. except Exception as e:
  674. logger.error(f"Error processing MQTT message: {e}")
  675. def publish_status(self):
  676. """Publish status updates periodically."""
  677. while self.running:
  678. try:
  679. # Update all states
  680. self._publish_running_state()
  681. self._publish_pattern_state()
  682. self._publish_playlist_state()
  683. self._publish_serial_state()
  684. self._publish_progress_state()
  685. # Update speed state
  686. self.client.publish(f"{self.speed_topic}/state", self.state.speed, retain=True)
  687. # Update LED state
  688. self._publish_led_state()
  689. # Publish keepalive status
  690. status = {
  691. "timestamp": time.time(),
  692. "client_id": self.client_id
  693. }
  694. self.client.publish(self.status_topic, json.dumps(status))
  695. # Wait for next interval
  696. time.sleep(self.status_interval)
  697. except Exception as e:
  698. logger.error(f"Error publishing status: {e}")
  699. time.sleep(5) # Wait before retry
  700. def start(self) -> None:
  701. """Start the MQTT handler."""
  702. if not self.is_enabled:
  703. return
  704. try:
  705. self.client.connect(self.broker, self.port)
  706. self.client.loop_start()
  707. # Start status publishing thread
  708. self.running = True
  709. self.status_thread = threading.Thread(target=self.publish_status, daemon=True)
  710. self.status_thread.start()
  711. # Get initial pattern and playlist lists
  712. self.patterns = list_theta_rho_files()
  713. self.playlists = list_all_playlists()
  714. # Wait a bit for MQTT connection to establish
  715. time.sleep(1)
  716. # Publish initial states
  717. self._publish_running_state()
  718. self._publish_pattern_state()
  719. self._publish_playlist_state()
  720. self._publish_serial_state()
  721. self._publish_progress_state()
  722. self._publish_led_state()
  723. # Setup Home Assistant discovery
  724. self.setup_ha_discovery()
  725. logger.info("MQTT Handler started successfully")
  726. except Exception as e:
  727. logger.error(f"Failed to start MQTT Handler: {e}")
  728. def stop(self) -> None:
  729. """Stop the MQTT handler."""
  730. if not self.is_enabled:
  731. return
  732. # First stop the running flag to prevent new iterations
  733. self.running = False
  734. # Clean up status thread
  735. local_status_thread = self.status_thread # Keep a local reference
  736. if local_status_thread and local_status_thread.is_alive():
  737. try:
  738. local_status_thread.join(timeout=5)
  739. if local_status_thread.is_alive():
  740. logger.warning("MQTT status thread did not terminate cleanly")
  741. except Exception as e:
  742. logger.error(f"Error joining status thread: {e}")
  743. self.status_thread = None
  744. # Clean up MQTT client
  745. try:
  746. if hasattr(self, 'client'):
  747. self.client.loop_stop()
  748. self.client.disconnect()
  749. except Exception as e:
  750. logger.error(f"Error disconnecting MQTT client: {e}")
  751. # Clean up main loop reference
  752. self.main_loop = None
  753. logger.info("MQTT handler stopped")
  754. @property
  755. def is_enabled(self) -> bool:
  756. """Return whether MQTT functionality is enabled.
  757. MQTT is enabled if:
  758. 1. A broker address is configured (either via state or env var), AND
  759. 2. Either state.mqtt_enabled is True, OR no UI config exists (env-only mode)
  760. """
  761. # If no broker configured, MQTT is disabled
  762. if not self.broker:
  763. return False
  764. # If state has mqtt_enabled explicitly set (UI was used), respect that setting
  765. # If mqtt_broker is set in state, user configured via UI - use mqtt_enabled
  766. if state.mqtt_broker:
  767. return state.mqtt_enabled
  768. # Otherwise, broker came from env vars - enable if broker exists
  769. return True
  770. @property
  771. def is_connected(self) -> bool:
  772. """Return whether MQTT client is currently connected to the broker."""
  773. return self._connected and self.is_enabled