1
0

handler.py 44 KB

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