handler.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. from .base import BaseMQTTHandler
  10. from dune_weaver_flask.modules.core.state import state
  11. from dune_weaver_flask.modules.core.pattern_manager import list_theta_rho_files
  12. from dune_weaver_flask.modules.core.playlist_manager import list_all_playlists
  13. from dune_weaver_flask.modules.serial.serial_manager import is_connected, get_port
  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 from environment variables
  19. self.broker = os.getenv('MQTT_BROKER')
  20. self.port = int(os.getenv('MQTT_PORT', '1883'))
  21. self.username = os.getenv('MQTT_USERNAME')
  22. self.password = os.getenv('MQTT_PASSWORD')
  23. self.client_id = os.getenv('MQTT_CLIENT_ID', 'dune_weaver')
  24. self.status_topic = os.getenv('MQTT_STATUS_TOPIC', 'dune_weaver/status')
  25. self.command_topic = os.getenv('MQTT_COMMAND_TOPIC', 'dune_weaver/command')
  26. self.status_interval = int(os.getenv('MQTT_STATUS_INTERVAL', '30'))
  27. # Store callback registry
  28. self.callback_registry = callback_registry
  29. # Threading control
  30. self.running = False
  31. self.status_thread = None
  32. # Home Assistant MQTT Discovery settings
  33. self.discovery_prefix = os.getenv('MQTT_DISCOVERY_PREFIX', 'homeassistant')
  34. self.device_name = os.getenv('HA_DEVICE_NAME', 'Dune Weaver')
  35. self.device_id = os.getenv('HA_DEVICE_ID', 'dune_weaver')
  36. # Additional topics for state
  37. self.running_state_topic = f"{self.device_id}/state/running"
  38. self.serial_state_topic = f"{self.device_id}/state/serial"
  39. self.pattern_select_topic = f"{self.device_id}/pattern/set"
  40. self.playlist_select_topic = f"{self.device_id}/playlist/set"
  41. self.speed_topic = f"{self.device_id}/speed/set"
  42. # Store current state
  43. self.current_file = ""
  44. self.is_running_state = False
  45. self.serial_state = ""
  46. self.patterns = []
  47. self.playlists = []
  48. # Initialize MQTT client if broker is configured
  49. if self.broker:
  50. self.client = mqtt.Client(client_id=self.client_id)
  51. self.client.on_connect = self.on_connect
  52. self.client.on_message = self.on_message
  53. if self.username and self.password:
  54. self.client.username_pw_set(self.username, self.password)
  55. self.state = state
  56. self.state.mqtt_handler = self # Set reference to self in state, needed so that state setters can update the state
  57. def setup_ha_discovery(self):
  58. """Publish Home Assistant MQTT discovery configurations."""
  59. if not self.is_enabled:
  60. return
  61. base_device = {
  62. "identifiers": [self.device_id],
  63. "name": self.device_name,
  64. "model": "Dune Weaver",
  65. "manufacturer": "DIY"
  66. }
  67. # Serial State Sensor
  68. serial_config = {
  69. "name": f"{self.device_name} Serial State",
  70. "unique_id": f"{self.device_id}_serial_state",
  71. "state_topic": self.serial_state_topic,
  72. "device": base_device,
  73. "icon": "mdi:serial-port",
  74. "entity_category": "diagnostic"
  75. }
  76. self._publish_discovery("sensor", "serial_state", serial_config)
  77. # Running State Sensor
  78. running_config = {
  79. "name": f"{self.device_name} Running State",
  80. "unique_id": f"{self.device_id}_running_state",
  81. "state_topic": self.running_state_topic,
  82. "device": base_device,
  83. "icon": "mdi:machine",
  84. "entity_category": "diagnostic"
  85. }
  86. self._publish_discovery("sensor", "running_state", running_config)
  87. # Stop Button
  88. stop_config = {
  89. "name": f"Stop pattern execution",
  90. "unique_id": f"{self.device_id}_stop",
  91. "command_topic": f"{self.device_id}/command/stop",
  92. "device": base_device,
  93. "icon": "mdi:stop",
  94. "entity_category": "config"
  95. }
  96. self._publish_discovery("button", "stop", stop_config)
  97. # Pause Button
  98. pause_config = {
  99. "name": f"Pause pattern execution",
  100. "unique_id": f"{self.device_id}_pause",
  101. "command_topic": f"{self.device_id}/command/pause",
  102. "state_topic": f"{self.device_id}/command/pause/state",
  103. "device": base_device,
  104. "icon": "mdi:pause",
  105. "entity_category": "config",
  106. "enabled_by_default": True,
  107. "availability": {
  108. "topic": f"{self.device_id}/command/pause/available",
  109. "payload_available": "true",
  110. "payload_not_available": "false"
  111. }
  112. }
  113. self._publish_discovery("button", "pause", pause_config)
  114. # Play Button
  115. play_config = {
  116. "name": f"Resume pattern execution",
  117. "unique_id": f"{self.device_id}_play",
  118. "command_topic": f"{self.device_id}/command/play",
  119. "state_topic": f"{self.device_id}/command/play/state",
  120. "device": base_device,
  121. "icon": "mdi:play",
  122. "entity_category": "config",
  123. "enabled_by_default": True,
  124. "availability": {
  125. "topic": f"{self.device_id}/command/play/available",
  126. "payload_available": "true",
  127. "payload_not_available": "false"
  128. }
  129. }
  130. self._publish_discovery("button", "play", play_config)
  131. # Speed Control
  132. speed_config = {
  133. "name": f"{self.device_name} Speed",
  134. "unique_id": f"{self.device_id}_speed",
  135. "command_topic": self.speed_topic,
  136. "state_topic": f"{self.speed_topic}/state",
  137. "device": base_device,
  138. "icon": "mdi:speedometer",
  139. "min": 50,
  140. "max": 1000,
  141. "step": 50
  142. }
  143. self._publish_discovery("number", "speed", speed_config)
  144. # Pattern Select
  145. pattern_config = {
  146. "name": f"{self.device_name} Pattern",
  147. "unique_id": f"{self.device_id}_pattern",
  148. "command_topic": self.pattern_select_topic,
  149. "state_topic": f"{self.pattern_select_topic}/state",
  150. "options": self.patterns,
  151. "device": base_device,
  152. "icon": "mdi:draw"
  153. }
  154. self._publish_discovery("select", "pattern", pattern_config)
  155. # Playlist Select
  156. playlist_config = {
  157. "name": f"{self.device_name} Playlist",
  158. "unique_id": f"{self.device_id}_playlist",
  159. "command_topic": self.playlist_select_topic,
  160. "state_topic": f"{self.playlist_select_topic}/state",
  161. "options": self.playlists,
  162. "device": base_device,
  163. "icon": "mdi:playlist-play"
  164. }
  165. self._publish_discovery("select", "playlist", playlist_config)
  166. def _publish_discovery(self, component: str, config_type: str, config: dict):
  167. """Helper method to publish HA discovery configs."""
  168. if not self.is_enabled:
  169. return
  170. discovery_topic = f"{self.discovery_prefix}/{component}/{self.device_id}/{config_type}/config"
  171. self.client.publish(discovery_topic, json.dumps(config), retain=True)
  172. def _publish_running_state(self, running_state=None):
  173. """Helper to publish running state and button availability."""
  174. if running_state is None:
  175. if not self.state.current_playing_file:
  176. running_state = "idle"
  177. elif self.state.pause_requested:
  178. running_state = "paused"
  179. else:
  180. running_state = "running"
  181. self.client.publish(self.running_state_topic, running_state, retain=True)
  182. # Update button availability based on state
  183. self.client.publish(f"{self.device_id}/command/pause/available",
  184. "true" if running_state == "running" else "false",
  185. retain=True)
  186. self.client.publish(f"{self.device_id}/command/play/available",
  187. "true" if running_state == "paused" else "false",
  188. retain=True)
  189. def _publish_pattern_state(self, current_file=None):
  190. """Helper to publish pattern state."""
  191. if current_file is None:
  192. current_file = self.state.current_playing_file
  193. if current_file:
  194. if current_file.startswith('./patterns/'):
  195. current_file = current_file[len('./patterns/'):]
  196. else:
  197. current_file = current_file.split("/")[-1].split("\\")[-1]
  198. self.client.publish(f"{self.pattern_select_topic}/state", current_file, retain=True)
  199. else:
  200. self.client.publish(f"{self.pattern_select_topic}/state", "None", retain=True)
  201. def _publish_playlist_state(self, playlist=None):
  202. """Helper to publish playlist state."""
  203. if playlist is None:
  204. playlist = self.state.current_playlist
  205. if playlist:
  206. self.client.publish(f"{self.playlist_select_topic}/state", playlist, retain=True)
  207. else:
  208. self.client.publish(f"{self.playlist_select_topic}/state", "None", retain=True)
  209. def _publish_serial_state(self):
  210. """Helper to publish serial state."""
  211. serial_connected = is_connected()
  212. serial_port = get_port() if serial_connected else None
  213. serial_status = f"connected to {serial_port}" if serial_connected else "disconnected"
  214. self.client.publish(self.serial_state_topic, serial_status, retain=True)
  215. def update_state(self, current_file=None, is_running=None, playlist=None):
  216. """Update state in Home Assistant. Only publishes the attributes that are explicitly passed."""
  217. if not self.is_enabled:
  218. return
  219. # Update pattern state if current_file is provided
  220. if current_file is not None:
  221. self._publish_pattern_state(current_file)
  222. # Update running state and button availability if is_running is provided
  223. if is_running is not None:
  224. running_state = "running" if is_running else "paused" if self.state.current_playing_file else "idle"
  225. self._publish_running_state(running_state)
  226. # Update playlist state if playlist info is provided
  227. if playlist is not None:
  228. self._publish_playlist_state(playlist)
  229. def on_connect(self, client, userdata, flags, rc):
  230. """Callback when connected to MQTT broker."""
  231. logger.info(f"Connected to MQTT broker with result code {rc}")
  232. # Subscribe to command topics
  233. client.subscribe([
  234. (self.command_topic, 0),
  235. (self.pattern_select_topic, 0),
  236. (self.playlist_select_topic, 0),
  237. (self.speed_topic, 0),
  238. (f"{self.device_id}/command/stop", 0),
  239. (f"{self.device_id}/command/pause", 0),
  240. (f"{self.device_id}/command/play", 0)
  241. ])
  242. # Publish discovery configurations
  243. self.setup_ha_discovery()
  244. def on_message(self, client, userdata, msg):
  245. """Callback when message is received."""
  246. try:
  247. if msg.topic == self.pattern_select_topic:
  248. # Handle pattern selection
  249. pattern_name = msg.payload.decode()
  250. if pattern_name in self.patterns:
  251. self.callback_registry['run_pattern'](file_path=f"{pattern_name}")
  252. self.client.publish(f"{self.pattern_select_topic}/state", pattern_name, retain=True)
  253. elif msg.topic == self.playlist_select_topic:
  254. # Handle playlist selection
  255. playlist_name = msg.payload.decode()
  256. if playlist_name in self.playlists:
  257. self.callback_registry['run_playlist'](playlist_name=playlist_name)
  258. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  259. elif msg.topic == self.speed_topic:
  260. speed = int(msg.payload.decode())
  261. self.callback_registry['set_speed'](speed)
  262. elif msg.topic == f"{self.device_id}/command/stop":
  263. # Handle stop command
  264. self.callback_registry['stop']()
  265. elif msg.topic == f"{self.device_id}/command/pause":
  266. # Handle pause command - only if in running state
  267. if bool(self.state.current_playing_file) and not self.state.pause_requested:
  268. self.callback_registry['pause']()
  269. elif msg.topic == f"{self.device_id}/command/play":
  270. # Handle play command - only if in paused state
  271. if bool(self.state.current_playing_file) and self.state.pause_requested:
  272. self.callback_registry['resume']()
  273. else:
  274. # Handle other commands
  275. payload = json.loads(msg.payload.decode())
  276. command = payload.get('command')
  277. params = payload.get('params', {})
  278. if command in self.callback_registry:
  279. self.callback_registry[command](**params)
  280. else:
  281. logger.error(f"Unknown command received: {command}")
  282. except json.JSONDecodeError:
  283. logger.error(f"Invalid JSON payload received: {msg.payload}")
  284. except Exception as e:
  285. logger.error(f"Error processing MQTT message: {e}")
  286. def publish_status(self):
  287. """Publish status updates periodically."""
  288. while self.running:
  289. try:
  290. # Update all states
  291. self._publish_running_state()
  292. self._publish_pattern_state()
  293. self._publish_playlist_state()
  294. self._publish_serial_state()
  295. # Update speed state
  296. self.client.publish(f"{self.speed_topic}/state", self.state.speed, retain=True)
  297. # Publish keepalive status
  298. status = {
  299. "timestamp": time.time(),
  300. "client_id": self.client_id
  301. }
  302. self.client.publish(self.status_topic, json.dumps(status))
  303. # Wait for next interval
  304. time.sleep(self.status_interval)
  305. except Exception as e:
  306. logger.error(f"Error publishing status: {e}")
  307. time.sleep(5) # Wait before retry
  308. def start(self) -> None:
  309. """Start the MQTT handler."""
  310. if not self.is_enabled:
  311. return
  312. try:
  313. self.client.connect(self.broker, self.port)
  314. self.client.loop_start()
  315. # Start status publishing thread
  316. self.running = True
  317. self.status_thread = threading.Thread(target=self.publish_status, daemon=True)
  318. self.status_thread.start()
  319. # Get initial pattern and playlist lists
  320. self.patterns = list_theta_rho_files()
  321. self.playlists = list_all_playlists()
  322. # Wait a bit for MQTT connection to establish
  323. time.sleep(1)
  324. # Publish initial states
  325. self._publish_running_state()
  326. self._publish_pattern_state()
  327. self._publish_playlist_state()
  328. self._publish_serial_state()
  329. # Setup Home Assistant discovery
  330. self.setup_ha_discovery()
  331. logger.info("MQTT Handler started successfully")
  332. except Exception as e:
  333. logger.error(f"Failed to start MQTT Handler: {e}")
  334. def stop(self) -> None:
  335. """Stop the MQTT handler."""
  336. if not self.is_enabled:
  337. return
  338. self.running = False
  339. if self.status_thread:
  340. self.status_thread.join(timeout=1)
  341. self.client.loop_stop()
  342. self.client.disconnect()
  343. @property
  344. def is_enabled(self) -> bool:
  345. """Return whether MQTT functionality is enabled."""
  346. return bool(self.broker)