1
0

handler.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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 from environment variables
  20. self.broker = os.getenv('MQTT_BROKER')
  21. self.port = int(os.getenv('MQTT_PORT', '1883'))
  22. self.username = os.getenv('MQTT_USERNAME')
  23. self.password = os.getenv('MQTT_PASSWORD')
  24. self.client_id = 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
  34. self.discovery_prefix = os.getenv('MQTT_DISCOVERY_PREFIX', 'homeassistant')
  35. self.device_name = os.getenv('HA_DEVICE_NAME', 'Dune Weaver')
  36. self.device_id = 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. # Store current state
  46. self.current_file = ""
  47. self.is_running_state = False
  48. self.serial_state = ""
  49. self.patterns = []
  50. self.playlists = []
  51. # Initialize MQTT client if broker is configured
  52. if self.broker:
  53. self.client = mqtt.Client(client_id=self.client_id)
  54. self.client.on_connect = self.on_connect
  55. self.client.on_message = self.on_message
  56. if self.username and self.password:
  57. self.client.username_pw_set(self.username, self.password)
  58. self.state = state
  59. self.state.mqtt_handler = self # Set reference to self in state, needed so that state setters can update the state
  60. # Store the main event loop during initialization
  61. self.main_loop = asyncio.get_event_loop()
  62. def setup_ha_discovery(self):
  63. """Publish Home Assistant MQTT discovery configurations."""
  64. if not self.is_enabled:
  65. return
  66. base_device = {
  67. "identifiers": [self.device_id],
  68. "name": self.device_name,
  69. "model": "Dune Weaver",
  70. "manufacturer": "DIY"
  71. }
  72. # Serial State Sensor
  73. serial_config = {
  74. "name": f"{self.device_name} Serial State",
  75. "unique_id": f"{self.device_id}_serial_state",
  76. "state_topic": self.serial_state_topic,
  77. "device": base_device,
  78. "icon": "mdi:serial-port",
  79. "entity_category": "diagnostic"
  80. }
  81. self._publish_discovery("sensor", "serial_state", serial_config)
  82. # Running State Sensor
  83. running_config = {
  84. "name": f"{self.device_name} Running State",
  85. "unique_id": f"{self.device_id}_running_state",
  86. "state_topic": self.running_state_topic,
  87. "device": base_device,
  88. "icon": "mdi:machine",
  89. "entity_category": "diagnostic"
  90. }
  91. self._publish_discovery("sensor", "running_state", running_config)
  92. # Stop Button
  93. stop_config = {
  94. "name": f"Stop pattern execution",
  95. "unique_id": f"{self.device_id}_stop",
  96. "command_topic": f"{self.device_id}/command/stop",
  97. "device": base_device,
  98. "icon": "mdi:stop",
  99. "entity_category": "config"
  100. }
  101. self._publish_discovery("button", "stop", stop_config)
  102. # Pause Button
  103. pause_config = {
  104. "name": f"Pause pattern execution",
  105. "unique_id": f"{self.device_id}_pause",
  106. "command_topic": f"{self.device_id}/command/pause",
  107. "state_topic": f"{self.device_id}/command/pause/state",
  108. "device": base_device,
  109. "icon": "mdi:pause",
  110. "entity_category": "config",
  111. "enabled_by_default": True,
  112. "availability": {
  113. "topic": f"{self.device_id}/command/pause/available",
  114. "payload_available": "true",
  115. "payload_not_available": "false"
  116. }
  117. }
  118. self._publish_discovery("button", "pause", pause_config)
  119. # Play Button
  120. play_config = {
  121. "name": f"Resume pattern execution",
  122. "unique_id": f"{self.device_id}_play",
  123. "command_topic": f"{self.device_id}/command/play",
  124. "state_topic": f"{self.device_id}/command/play/state",
  125. "device": base_device,
  126. "icon": "mdi:play",
  127. "entity_category": "config",
  128. "enabled_by_default": True,
  129. "availability": {
  130. "topic": f"{self.device_id}/command/play/available",
  131. "payload_available": "true",
  132. "payload_not_available": "false"
  133. }
  134. }
  135. self._publish_discovery("button", "play", play_config)
  136. # Speed Control
  137. speed_config = {
  138. "name": f"{self.device_name} Speed",
  139. "unique_id": f"{self.device_id}_speed",
  140. "command_topic": self.speed_topic,
  141. "state_topic": f"{self.speed_topic}/state",
  142. "device": base_device,
  143. "icon": "mdi:speedometer",
  144. "mode": "box",
  145. "min": 50,
  146. "max": 2000,
  147. "step": 50
  148. }
  149. self._publish_discovery("number", "speed", speed_config)
  150. # Pattern Select
  151. pattern_config = {
  152. "name": f"{self.device_name} Pattern",
  153. "unique_id": f"{self.device_id}_pattern",
  154. "command_topic": self.pattern_select_topic,
  155. "state_topic": f"{self.pattern_select_topic}/state",
  156. "options": self.patterns,
  157. "device": base_device,
  158. "icon": "mdi:draw"
  159. }
  160. self._publish_discovery("select", "pattern", pattern_config)
  161. # Playlist Select
  162. playlist_config = {
  163. "name": f"{self.device_name} Playlist",
  164. "unique_id": f"{self.device_id}_playlist",
  165. "command_topic": self.playlist_select_topic,
  166. "state_topic": f"{self.playlist_select_topic}/state",
  167. "options": self.playlists,
  168. "device": base_device,
  169. "icon": "mdi:playlist-play"
  170. }
  171. self._publish_discovery("select", "playlist", playlist_config)
  172. # Playlist Run Mode Select
  173. playlist_mode_config = {
  174. "name": f"{self.device_name} Playlist Mode",
  175. "unique_id": f"{self.device_id}_playlist_mode",
  176. "command_topic": f"{self.device_id}/playlist/mode/set",
  177. "state_topic": f"{self.device_id}/playlist/mode/state",
  178. "options": ["single", "loop"],
  179. "device": base_device,
  180. "icon": "mdi:repeat",
  181. "entity_category": "config"
  182. }
  183. self._publish_discovery("select", "playlist_mode", playlist_mode_config)
  184. # Playlist Pause Time Number Input
  185. pause_time_config = {
  186. "name": f"{self.device_name} Playlist Pause Time",
  187. "unique_id": f"{self.device_id}_pause_time",
  188. "command_topic": f"{self.device_id}/playlist/pause_time/set",
  189. "state_topic": f"{self.device_id}/playlist/pause_time/state",
  190. "device": base_device,
  191. "icon": "mdi:timer",
  192. "entity_category": "config",
  193. "mode": "box",
  194. "unit_of_measurement": "seconds",
  195. "min": 0,
  196. "max": 86400,
  197. }
  198. self._publish_discovery("number", "pause_time", pause_time_config)
  199. # Clear Pattern Select
  200. clear_pattern_config = {
  201. "name": f"{self.device_name} Clear Pattern",
  202. "unique_id": f"{self.device_id}_clear_pattern",
  203. "command_topic": f"{self.device_id}/playlist/clear_pattern/set",
  204. "state_topic": f"{self.device_id}/playlist/clear_pattern/state",
  205. "options": ["none", "random", "adaptive", "clear_from_in", "clear_from_out", "clear_sideway"],
  206. "device": base_device,
  207. "icon": "mdi:eraser",
  208. "entity_category": "config"
  209. }
  210. self._publish_discovery("select", "clear_pattern", clear_pattern_config)
  211. # Completion Percentage Sensor
  212. completion_config = {
  213. "name": f"{self.device_name} Completion",
  214. "unique_id": f"{self.device_id}_completion",
  215. "state_topic": self.completion_topic,
  216. "device": base_device,
  217. "icon": "mdi:progress-clock",
  218. "unit_of_measurement": "%",
  219. "state_class": "measurement",
  220. "entity_category": "diagnostic"
  221. }
  222. self._publish_discovery("sensor", "completion", completion_config)
  223. # Time Remaining Sensor
  224. time_remaining_config = {
  225. "name": f"{self.device_name} Time Remaining",
  226. "unique_id": f"{self.device_id}_time_remaining",
  227. "state_topic": self.time_remaining_topic,
  228. "device": base_device,
  229. "icon": "mdi:timer-sand",
  230. "unit_of_measurement": "s",
  231. "device_class": "duration",
  232. "state_class": "measurement",
  233. "entity_category": "diagnostic"
  234. }
  235. self._publish_discovery("sensor", "time_remaining", time_remaining_config)
  236. def _publish_discovery(self, component: str, config_type: str, config: dict):
  237. """Helper method to publish HA discovery configs."""
  238. if not self.is_enabled:
  239. return
  240. discovery_topic = f"{self.discovery_prefix}/{component}/{self.device_id}/{config_type}/config"
  241. self.client.publish(discovery_topic, json.dumps(config), retain=True)
  242. def _publish_running_state(self, running_state=None):
  243. """Helper to publish running state and button availability."""
  244. if running_state is None:
  245. if not self.state.current_playing_file:
  246. running_state = "idle"
  247. elif self.state.pause_requested:
  248. running_state = "paused"
  249. else:
  250. running_state = "running"
  251. self.client.publish(self.running_state_topic, running_state, retain=True)
  252. # Update button availability based on state
  253. self.client.publish(f"{self.device_id}/command/pause/available",
  254. "true" if running_state == "running" else "false",
  255. retain=True)
  256. self.client.publish(f"{self.device_id}/command/play/available",
  257. "true" if running_state == "paused" else "false",
  258. retain=True)
  259. def _publish_pattern_state(self, current_file=None):
  260. """Helper to publish pattern state."""
  261. if current_file is None:
  262. current_file = self.state.current_playing_file
  263. if current_file:
  264. if current_file.startswith('./patterns/'):
  265. current_file = current_file[len('./patterns/'):]
  266. else:
  267. current_file = current_file.split("/")[-1].split("\\")[-1]
  268. self.client.publish(f"{self.pattern_select_topic}/state", current_file, retain=True)
  269. else:
  270. # Clear the pattern selection
  271. self.client.publish(f"{self.pattern_select_topic}/state", "None", retain=True)
  272. def _publish_playlist_state(self, playlist_name=None):
  273. """Helper to publish playlist state."""
  274. if playlist_name is None:
  275. playlist_name = self.state.current_playlist_name
  276. if playlist_name:
  277. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  278. else:
  279. # Clear the playlist selection
  280. self.client.publish(f"{self.playlist_select_topic}/state", "None", retain=True)
  281. def _publish_serial_state(self):
  282. """Helper to publish serial state."""
  283. serial_connected = (state.conn.is_connected() if state.conn else False)
  284. serial_port = state.port if serial_connected else None
  285. serial_status = f"connected to {serial_port}" if serial_connected else "disconnected"
  286. self.client.publish(self.serial_state_topic, serial_status, retain=True)
  287. def _publish_progress_state(self):
  288. """Helper to publish completion percentage and time remaining."""
  289. if state.execution_progress:
  290. current, total, remaining_time, elapsed_time = state.execution_progress
  291. completion_percentage = (current / total * 100) if total > 0 else 0
  292. # Publish completion percentage (rounded to 1 decimal place)
  293. self.client.publish(self.completion_topic, round(completion_percentage, 1), retain=True)
  294. # Publish time remaining (rounded to nearest second, defaulting to 0 if None)
  295. time_remaining_seconds = round(remaining_time) if remaining_time is not None else 0
  296. self.client.publish(self.time_remaining_topic, max(0, time_remaining_seconds), retain=True)
  297. else:
  298. # No pattern running, publish zeros
  299. self.client.publish(self.completion_topic, 0, retain=True)
  300. self.client.publish(self.time_remaining_topic, 0, retain=True)
  301. def update_state(self, current_file=None, is_running=None, playlist=None, playlist_name=None):
  302. """Update state in Home Assistant. Only publishes the attributes that are explicitly passed."""
  303. if not self.is_enabled:
  304. return
  305. # Update pattern state if current_file is provided
  306. if current_file is not None:
  307. self._publish_pattern_state(current_file)
  308. # Update running state and button availability if is_running is provided
  309. if is_running is not None:
  310. running_state = "running" if is_running else "paused" if self.state.current_playing_file else "idle"
  311. self._publish_running_state(running_state)
  312. # Update playlist state if playlist info is provided
  313. if playlist_name is not None:
  314. self._publish_playlist_state(playlist_name)
  315. def on_connect(self, client, userdata, flags, rc):
  316. """Callback when connected to MQTT broker."""
  317. if rc == 0:
  318. logger.info("MQTT Connection Accepted.")
  319. # Subscribe to command topics
  320. client.subscribe([
  321. (self.command_topic, 0),
  322. (self.pattern_select_topic, 0),
  323. (self.playlist_select_topic, 0),
  324. (self.speed_topic, 0),
  325. (f"{self.device_id}/command/stop", 0),
  326. (f"{self.device_id}/command/pause", 0),
  327. (f"{self.device_id}/command/play", 0),
  328. (f"{self.device_id}/playlist/mode/set", 0),
  329. (f"{self.device_id}/playlist/pause_time/set", 0),
  330. (f"{self.device_id}/playlist/clear_pattern/set", 0),
  331. ])
  332. # Publish discovery configurations
  333. self.setup_ha_discovery()
  334. elif rc == 1:
  335. logger.error("MQTT Connection Refused. Protocol level not supported.")
  336. elif rc == 2:
  337. logger.error("MQTT Connection Refused. The client-identifier is not allowed by the server.")
  338. elif rc == 3:
  339. logger.error("MQTT Connection Refused. The MQTT service is not available.")
  340. elif rc == 4:
  341. logger.error("MQTT Connection Refused. The data in the username or password is malformed.")
  342. elif rc == 5:
  343. logger.error("MQTT Connection Refused. The client is not authorized to connect.")
  344. else:
  345. logger.error(f"MQTT Connection Refused. Unknown error code: {rc}")
  346. def on_message(self, client, userdata, msg):
  347. """Callback when message is received."""
  348. try:
  349. if msg.topic == self.pattern_select_topic:
  350. from modules.core.pattern_manager import THETA_RHO_DIR
  351. # Handle pattern selection
  352. pattern_name = msg.payload.decode()
  353. if pattern_name in self.patterns:
  354. # Schedule the coroutine to run in the main event loop
  355. asyncio.run_coroutine_threadsafe(
  356. self.callback_registry['run_pattern'](file_path=f"{THETA_RHO_DIR}/{pattern_name}"),
  357. self.main_loop
  358. ).add_done_callback(
  359. lambda _: self._publish_pattern_state(None) # Clear pattern after execution
  360. )
  361. self.client.publish(f"{self.pattern_select_topic}/state", pattern_name, retain=True)
  362. elif msg.topic == self.playlist_select_topic:
  363. # Handle playlist selection
  364. playlist_name = msg.payload.decode()
  365. if playlist_name in self.playlists:
  366. # Schedule the coroutine to run in the main event loop
  367. asyncio.run_coroutine_threadsafe(
  368. self.callback_registry['run_playlist'](
  369. playlist_name=playlist_name,
  370. run_mode=self.state.playlist_mode,
  371. pause_time=self.state.pause_time,
  372. clear_pattern=self.state.clear_pattern
  373. ),
  374. self.main_loop
  375. ).add_done_callback(
  376. lambda _: self._publish_playlist_state(None) # Clear playlist after execution
  377. )
  378. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  379. elif msg.topic == self.speed_topic:
  380. speed = int(msg.payload.decode())
  381. self.callback_registry['set_speed'](speed)
  382. elif msg.topic == f"{self.device_id}/command/stop":
  383. # Handle stop command
  384. callback = self.callback_registry['stop']
  385. if asyncio.iscoroutinefunction(callback):
  386. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  387. else:
  388. callback()
  389. # Clear both pattern and playlist selections
  390. self._publish_pattern_state(None)
  391. self._publish_playlist_state(None)
  392. elif msg.topic == f"{self.device_id}/command/pause":
  393. # Handle pause command - only if in running state
  394. if bool(self.state.current_playing_file) and not self.state.pause_requested:
  395. # Check if callback is async or sync
  396. callback = self.callback_registry['pause']
  397. if asyncio.iscoroutinefunction(callback):
  398. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  399. else:
  400. callback()
  401. elif msg.topic == f"{self.device_id}/command/play":
  402. # Handle play command - only if in paused state
  403. if bool(self.state.current_playing_file) and self.state.pause_requested:
  404. # Check if callback is async or sync
  405. callback = self.callback_registry['resume']
  406. if asyncio.iscoroutinefunction(callback):
  407. asyncio.run_coroutine_threadsafe(callback(), self.main_loop)
  408. else:
  409. callback()
  410. elif msg.topic == f"{self.device_id}/playlist/mode/set":
  411. mode = msg.payload.decode()
  412. if mode in ["single", "loop"]:
  413. state.playlist_mode = mode
  414. self.client.publish(f"{self.device_id}/playlist/mode/state", mode, retain=True)
  415. elif msg.topic == f"{self.device_id}/playlist/pause_time/set":
  416. pause_time = float(msg.payload.decode())
  417. if 0 <= pause_time <= 60:
  418. state.pause_time = pause_time
  419. self.client.publish(f"{self.device_id}/playlist/pause_time/state", pause_time, retain=True)
  420. elif msg.topic == f"{self.device_id}/playlist/clear_pattern/set":
  421. clear_pattern = msg.payload.decode()
  422. if clear_pattern in ["none", "random", "adaptive", "clear_from_in", "clear_from_out", "clear_sideway"]:
  423. state.clear_pattern = clear_pattern
  424. self.client.publish(f"{self.device_id}/playlist/clear_pattern/state", clear_pattern, retain=True)
  425. else:
  426. # Handle other commands
  427. payload = json.loads(msg.payload.decode())
  428. command = payload.get('command')
  429. params = payload.get('params', {})
  430. if command in self.callback_registry:
  431. self.callback_registry[command](**params)
  432. else:
  433. logger.error(f"Unknown command received: {command}")
  434. except json.JSONDecodeError:
  435. logger.error(f"Invalid JSON payload received: {msg.payload}")
  436. except Exception as e:
  437. logger.error(f"Error processing MQTT message: {e}")
  438. def publish_status(self):
  439. """Publish status updates periodically."""
  440. while self.running:
  441. try:
  442. # Update all states
  443. self._publish_running_state()
  444. self._publish_pattern_state()
  445. self._publish_playlist_state()
  446. self._publish_serial_state()
  447. self._publish_progress_state()
  448. # Update speed state
  449. self.client.publish(f"{self.speed_topic}/state", self.state.speed, retain=True)
  450. # Publish keepalive status
  451. status = {
  452. "timestamp": time.time(),
  453. "client_id": self.client_id
  454. }
  455. self.client.publish(self.status_topic, json.dumps(status))
  456. # Wait for next interval
  457. time.sleep(self.status_interval)
  458. except Exception as e:
  459. logger.error(f"Error publishing status: {e}")
  460. time.sleep(5) # Wait before retry
  461. def start(self) -> None:
  462. """Start the MQTT handler."""
  463. if not self.is_enabled:
  464. return
  465. try:
  466. self.client.connect(self.broker, self.port)
  467. self.client.loop_start()
  468. # Start status publishing thread
  469. self.running = True
  470. self.status_thread = threading.Thread(target=self.publish_status, daemon=True)
  471. self.status_thread.start()
  472. # Get initial pattern and playlist lists
  473. self.patterns = list_theta_rho_files()
  474. self.playlists = list_all_playlists()
  475. # Wait a bit for MQTT connection to establish
  476. time.sleep(1)
  477. # Publish initial states
  478. self._publish_running_state()
  479. self._publish_pattern_state()
  480. self._publish_playlist_state()
  481. self._publish_serial_state()
  482. self._publish_progress_state()
  483. # Setup Home Assistant discovery
  484. self.setup_ha_discovery()
  485. logger.info("MQTT Handler started successfully")
  486. except Exception as e:
  487. logger.error(f"Failed to start MQTT Handler: {e}")
  488. def stop(self) -> None:
  489. """Stop the MQTT handler."""
  490. if not self.is_enabled:
  491. return
  492. # First stop the running flag to prevent new iterations
  493. self.running = False
  494. # Clean up status thread
  495. local_status_thread = self.status_thread # Keep a local reference
  496. if local_status_thread and local_status_thread.is_alive():
  497. try:
  498. local_status_thread.join(timeout=5)
  499. if local_status_thread.is_alive():
  500. logger.warning("MQTT status thread did not terminate cleanly")
  501. except Exception as e:
  502. logger.error(f"Error joining status thread: {e}")
  503. self.status_thread = None
  504. # Clean up MQTT client
  505. try:
  506. if hasattr(self, 'client'):
  507. self.client.loop_stop()
  508. self.client.disconnect()
  509. except Exception as e:
  510. logger.error(f"Error disconnecting MQTT client: {e}")
  511. # Clean up main loop reference
  512. self.main_loop = None
  513. logger.info("MQTT handler stopped")
  514. @property
  515. def is_enabled(self) -> bool:
  516. """Return whether MQTT functionality is enabled."""
  517. return bool(self.broker)