1
0

handler.py 47 KB

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