handler.py 23 KB

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