handler.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. "min": 50,
  143. "max": 1000,
  144. "step": 50
  145. }
  146. self._publish_discovery("number", "speed", speed_config)
  147. # Pattern Select
  148. pattern_config = {
  149. "name": f"{self.device_name} Pattern",
  150. "unique_id": f"{self.device_id}_pattern",
  151. "command_topic": self.pattern_select_topic,
  152. "state_topic": f"{self.pattern_select_topic}/state",
  153. "options": self.patterns,
  154. "device": base_device,
  155. "icon": "mdi:draw"
  156. }
  157. self._publish_discovery("select", "pattern", pattern_config)
  158. # Playlist Select
  159. playlist_config = {
  160. "name": f"{self.device_name} Playlist",
  161. "unique_id": f"{self.device_id}_playlist",
  162. "command_topic": self.playlist_select_topic,
  163. "state_topic": f"{self.playlist_select_topic}/state",
  164. "options": self.playlists,
  165. "device": base_device,
  166. "icon": "mdi:playlist-play"
  167. }
  168. self._publish_discovery("select", "playlist", playlist_config)
  169. def _publish_discovery(self, component: str, config_type: str, config: dict):
  170. """Helper method to publish HA discovery configs."""
  171. if not self.is_enabled:
  172. return
  173. discovery_topic = f"{self.discovery_prefix}/{component}/{self.device_id}/{config_type}/config"
  174. self.client.publish(discovery_topic, json.dumps(config), retain=True)
  175. def _publish_running_state(self, running_state=None):
  176. """Helper to publish running state and button availability."""
  177. if running_state is None:
  178. if not self.state.current_playing_file:
  179. running_state = "idle"
  180. elif self.state.pause_requested:
  181. running_state = "paused"
  182. else:
  183. running_state = "running"
  184. self.client.publish(self.running_state_topic, running_state, retain=True)
  185. # Update button availability based on state
  186. self.client.publish(f"{self.device_id}/command/pause/available",
  187. "true" if running_state == "running" else "false",
  188. retain=True)
  189. self.client.publish(f"{self.device_id}/command/play/available",
  190. "true" if running_state == "paused" else "false",
  191. retain=True)
  192. def _publish_pattern_state(self, current_file=None):
  193. """Helper to publish pattern state."""
  194. if current_file is None:
  195. current_file = self.state.current_playing_file
  196. if current_file:
  197. if current_file.startswith('./patterns/'):
  198. current_file = current_file[len('./patterns/'):]
  199. else:
  200. current_file = current_file.split("/")[-1].split("\\")[-1]
  201. self.client.publish(f"{self.pattern_select_topic}/state", current_file, retain=True)
  202. else:
  203. self.client.publish(f"{self.pattern_select_topic}/state", "None", retain=True)
  204. def _publish_playlist_state(self, playlist_name=None):
  205. """Helper to publish playlist state."""
  206. if playlist_name is None:
  207. playlist_name = self.state.current_playlist_name
  208. if playlist_name:
  209. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  210. else:
  211. self.client.publish(f"{self.playlist_select_topic}/state", "None", retain=True)
  212. def _publish_serial_state(self):
  213. """Helper to publish serial state."""
  214. serial_connected = (state.conn.is_connected() if state.conn else False)
  215. serial_port = state.port if serial_connected else None
  216. serial_status = f"connected to {serial_port}" if serial_connected else "disconnected"
  217. self.client.publish(self.serial_state_topic, serial_status, retain=True)
  218. def update_state(self, current_file=None, is_running=None, playlist=None, playlist_name=None):
  219. """Update state in Home Assistant. Only publishes the attributes that are explicitly passed."""
  220. if not self.is_enabled:
  221. return
  222. # Update pattern state if current_file is provided
  223. if current_file is not None:
  224. self._publish_pattern_state(current_file)
  225. # Update running state and button availability if is_running is provided
  226. if is_running is not None:
  227. running_state = "running" if is_running else "paused" if self.state.current_playing_file else "idle"
  228. self._publish_running_state(running_state)
  229. # Update playlist state if playlist info is provided
  230. if playlist_name is not None:
  231. self._publish_playlist_state(playlist_name)
  232. def on_connect(self, client, userdata, flags, rc):
  233. """Callback when connected to MQTT broker."""
  234. if rc == 0:
  235. logger.info("MQTT Connection Accepted.")
  236. # Subscribe to command topics
  237. client.subscribe([
  238. (self.command_topic, 0),
  239. (self.pattern_select_topic, 0),
  240. (self.playlist_select_topic, 0),
  241. (self.speed_topic, 0),
  242. (f"{self.device_id}/command/stop", 0),
  243. (f"{self.device_id}/command/pause", 0),
  244. (f"{self.device_id}/command/play", 0)
  245. ])
  246. # Publish discovery configurations
  247. self.setup_ha_discovery()
  248. elif rc == 1:
  249. logger.error("MQTT Connection Refused. Protocol level not supported.")
  250. elif rc == 2:
  251. logger.error("MQTT Connection Refused. The client-identifier is not allowed by the server.")
  252. elif rc == 3:
  253. logger.error("MQTT Connection Refused. The MQTT service is not available.")
  254. elif rc == 4:
  255. logger.error("MQTT Connection Refused. The data in the username or password is malformed.")
  256. elif rc == 5:
  257. logger.error("MQTT Connection Refused. The client is not authorized to connect.")
  258. else:
  259. logger.error(f"MQTT Connection Refused. Unknown error code: {rc}")
  260. def on_message(self, client, userdata, msg):
  261. """Callback when message is received."""
  262. try:
  263. if msg.topic == self.pattern_select_topic:
  264. from modules.core.pattern_manager import THETA_RHO_DIR
  265. # Handle pattern selection
  266. pattern_name = msg.payload.decode()
  267. if pattern_name in self.patterns:
  268. # Schedule the coroutine to run in the main event loop
  269. asyncio.run_coroutine_threadsafe(
  270. self.callback_registry['run_pattern'](file_path=f"{THETA_RHO_DIR}/{pattern_name}"),
  271. self.main_loop
  272. )
  273. self.client.publish(f"{self.pattern_select_topic}/state", pattern_name, retain=True)
  274. elif msg.topic == self.playlist_select_topic:
  275. # Handle playlist selection
  276. playlist_name = msg.payload.decode()
  277. if playlist_name in self.playlists:
  278. # Schedule the coroutine to run in the main event loop
  279. asyncio.run_coroutine_threadsafe(
  280. self.callback_registry['run_playlist'](playlist_name=playlist_name),
  281. self.main_loop
  282. )
  283. self.client.publish(f"{self.playlist_select_topic}/state", playlist_name, retain=True)
  284. elif msg.topic == self.speed_topic:
  285. speed = int(msg.payload.decode())
  286. self.callback_registry['set_speed'](speed)
  287. elif msg.topic == f"{self.device_id}/command/stop":
  288. # Handle stop command
  289. self.callback_registry['stop']()
  290. elif msg.topic == f"{self.device_id}/command/pause":
  291. # Handle pause command - only if in running state
  292. if bool(self.state.current_playing_file) and not self.state.pause_requested:
  293. self.callback_registry['pause']()
  294. elif msg.topic == f"{self.device_id}/command/play":
  295. # Handle play command - only if in paused state
  296. if bool(self.state.current_playing_file) and self.state.pause_requested:
  297. self.callback_registry['resume']()
  298. else:
  299. # Handle other commands
  300. payload = json.loads(msg.payload.decode())
  301. command = payload.get('command')
  302. params = payload.get('params', {})
  303. if command in self.callback_registry:
  304. self.callback_registry[command](**params)
  305. else:
  306. logger.error(f"Unknown command received: {command}")
  307. except json.JSONDecodeError:
  308. logger.error(f"Invalid JSON payload received: {msg.payload}")
  309. except Exception as e:
  310. logger.error(f"Error processing MQTT message: {e}")
  311. def publish_status(self):
  312. """Publish status updates periodically."""
  313. while self.running:
  314. try:
  315. # Update all states
  316. self._publish_running_state()
  317. self._publish_pattern_state()
  318. self._publish_playlist_state()
  319. self._publish_serial_state()
  320. # Update speed state
  321. self.client.publish(f"{self.speed_topic}/state", self.state.speed, retain=True)
  322. # Publish keepalive status
  323. status = {
  324. "timestamp": time.time(),
  325. "client_id": self.client_id
  326. }
  327. self.client.publish(self.status_topic, json.dumps(status))
  328. # Wait for next interval
  329. time.sleep(self.status_interval)
  330. except Exception as e:
  331. logger.error(f"Error publishing status: {e}")
  332. time.sleep(5) # Wait before retry
  333. def start(self) -> None:
  334. """Start the MQTT handler."""
  335. if not self.is_enabled:
  336. return
  337. try:
  338. self.client.connect(self.broker, self.port)
  339. self.client.loop_start()
  340. # Start status publishing thread
  341. self.running = True
  342. self.status_thread = threading.Thread(target=self.publish_status, daemon=True)
  343. self.status_thread.start()
  344. # Get initial pattern and playlist lists
  345. self.patterns = list_theta_rho_files()
  346. self.playlists = list_all_playlists()
  347. # Wait a bit for MQTT connection to establish
  348. time.sleep(1)
  349. # Publish initial states
  350. self._publish_running_state()
  351. self._publish_pattern_state()
  352. self._publish_playlist_state()
  353. self._publish_serial_state()
  354. # Setup Home Assistant discovery
  355. self.setup_ha_discovery()
  356. logger.info("MQTT Handler started successfully")
  357. except Exception as e:
  358. logger.error(f"Failed to start MQTT Handler: {e}")
  359. def stop(self) -> None:
  360. """Stop the MQTT handler."""
  361. if not self.is_enabled:
  362. return
  363. self.running = False
  364. if self.status_thread:
  365. self.status_thread.join(timeout=1)
  366. self.client.loop_stop()
  367. self.client.disconnect()
  368. @property
  369. def is_enabled(self) -> bool:
  370. """Return whether MQTT functionality is enabled."""
  371. return bool(self.broker)