mqtt_relay.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. """MQTT Relay Service for publishing BamBuddy events to external MQTT brokers.
  2. This service enables integration with external automation systems like
  3. Node-RED, Home Assistant, and other MQTT-based platforms.
  4. """
  5. import asyncio
  6. import json
  7. import logging
  8. import ssl
  9. import threading
  10. import time
  11. from datetime import datetime, timezone
  12. from typing import Any
  13. import paho.mqtt.client as mqtt
  14. from backend.app.utils.paho_teardown import retire_paho_client
  15. logger = logging.getLogger(__name__)
  16. # Fields the printer status topic takes from the same dict the REST status and the
  17. # WebSocket send, so a subscriber reads them in the shape it already knows (#3401).
  18. _STATUS_FIELDS_FROM_STATE = ("door_open", "active_extruder", "tray_now", "ams", "vt_tray", "hms_errors")
  19. class MQTTRelayService:
  20. """Publishes BamBuddy events to an external MQTT broker."""
  21. # Minimum interval between status updates per printer (seconds)
  22. STATUS_THROTTLE_SECONDS = 1.0
  23. def __init__(self):
  24. self.client: mqtt.Client | None = None
  25. self.enabled = False
  26. self.connected = False
  27. self.topic_prefix = "bambuddy"
  28. self._lock = threading.Lock()
  29. self._loop: asyncio.AbstractEventLoop | None = None
  30. self._broker = ""
  31. self._port = 1883
  32. self._last_printer_status: dict[int, float] = {} # printer_id -> last publish timestamp
  33. self._last_printer_connected: dict[int, bool] = {} # printer_id -> `connected` in the last publish
  34. self._smart_plug_service = None # Lazy import to avoid circular dependency
  35. self._settings: dict = {} # Store settings for smart plug service
  36. self._disconnection_event: threading.Event | None = None
  37. async def configure(self, settings: dict) -> bool:
  38. """Configure MQTT connection from settings.
  39. Returns True if connection was successful or MQTT is disabled.
  40. """
  41. self.enabled = settings.get("mqtt_enabled", False)
  42. self._settings = settings # Store for smart plug service
  43. if not self.enabled:
  44. await self.disconnect()
  45. # Also configure smart plug service (will disable it)
  46. await self._configure_smart_plug_service(settings)
  47. logger.info("MQTT relay disabled")
  48. return True
  49. broker = settings.get("mqtt_broker", "")
  50. port = settings.get("mqtt_port", 1883)
  51. username = settings.get("mqtt_username", "")
  52. password = settings.get("mqtt_password", "")
  53. self.topic_prefix = settings.get("mqtt_topic_prefix", "bambuddy")
  54. use_tls = settings.get("mqtt_use_tls", False)
  55. if not broker:
  56. logger.warning("MQTT enabled but no broker configured")
  57. return False
  58. # Store for status endpoint
  59. self._broker = broker
  60. self._port = port
  61. # Disconnect existing connection if settings changed
  62. if self.client:
  63. await self.disconnect()
  64. # Create and connect client
  65. result = await self._connect(broker, port, username, password, use_tls)
  66. # Configure smart plug service with same settings
  67. await self._configure_smart_plug_service(settings)
  68. return result
  69. async def _configure_smart_plug_service(self, settings: dict):
  70. """Configure the MQTT smart plug service with the same broker settings."""
  71. try:
  72. if self._smart_plug_service is None:
  73. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  74. self._smart_plug_service = mqtt_smart_plug_service
  75. await self._smart_plug_service.configure(settings)
  76. except Exception as e:
  77. logger.error("Failed to configure MQTT smart plug service: %s", e)
  78. @property
  79. def smart_plug_service(self):
  80. """Get the MQTT smart plug service instance."""
  81. if self._smart_plug_service is None:
  82. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  83. self._smart_plug_service = mqtt_smart_plug_service
  84. return self._smart_plug_service
  85. async def _connect(self, broker: str, port: int, username: str, password: str, use_tls: bool) -> bool:
  86. """Establish MQTT connection."""
  87. try:
  88. # Create client with callback API version 2 (use MQTTv311 for broader compatibility)
  89. self.client = mqtt.Client(
  90. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  91. client_id=f"bambuddy-{id(self)}",
  92. protocol=mqtt.MQTTv311,
  93. )
  94. # Last Will: the broker publishes this when the connection drops without a
  95. # clean disconnect (crash, killed container), which would otherwise leave the
  96. # retained "online" in place for good (#3401). It replaces that retained message.
  97. self.client.will_set(f"{self.topic_prefix}/status", json.dumps({"status": "offline"}), qos=1, retain=True)
  98. # Set up callbacks
  99. self.client.on_connect = self._on_connect
  100. self.client.on_disconnect = self._on_disconnect
  101. # Configure authentication
  102. if username:
  103. self.client.username_pw_set(username, password)
  104. # Configure TLS (allow self-signed certs for testing)
  105. if use_tls:
  106. self.client.tls_set(cert_reqs=ssl.CERT_NONE)
  107. self.client.tls_insecure_set(True) # Allow self-signed certs
  108. # Run connect_async in thread pool with timeout to avoid blocking
  109. # on unreachable brokers (connect_async does synchronous socket creation)
  110. try:
  111. await asyncio.wait_for(asyncio.to_thread(self.client.connect_async, broker, port, 60), timeout=3.0)
  112. except TimeoutError:
  113. logger.warning("MQTT relay connection to %s:%s timed out", broker, port)
  114. return False
  115. self.client.loop_start()
  116. # Wait briefly for connection callback
  117. await asyncio.sleep(1.0)
  118. if self.connected:
  119. logger.info("MQTT relay connected to %s:%s", broker, port)
  120. # Publish online status
  121. self._publish_status("online")
  122. return True
  123. else:
  124. logger.warning("MQTT relay connection pending to %s:%s", broker, port)
  125. return True # Connection is async, may succeed later
  126. except Exception as e:
  127. logger.error("MQTT relay connection failed: %s", e)
  128. self.connected = False
  129. return False
  130. def _on_connect(
  131. self,
  132. client: mqtt.Client,
  133. userdata: Any,
  134. flags: dict,
  135. reason_code: int | mqtt.ReasonCode,
  136. properties: mqtt.Properties | None = None,
  137. ):
  138. """Callback when connected to broker."""
  139. # Handle both MQTTv311 (int) and MQTTv5 (ReasonCode) return codes
  140. rc = reason_code if isinstance(reason_code, int) else reason_code.value
  141. if rc == 0:
  142. self.connected = True
  143. logger.info("MQTT relay connected successfully")
  144. # Publish online status
  145. self._publish_status("online")
  146. else:
  147. self.connected = False
  148. logger.error("MQTT relay connection failed: %s", reason_code)
  149. def _on_disconnect(
  150. self,
  151. client: mqtt.Client,
  152. userdata: Any,
  153. flags_or_rc: dict | int | mqtt.ReasonCode,
  154. reason_code: int | mqtt.ReasonCode | None = None,
  155. properties: mqtt.Properties | None = None,
  156. ):
  157. """Callback when disconnected from broker."""
  158. self.connected = False
  159. # Handle both MQTTv311 (rc as 3rd param) and MQTTv5 (flags, rc, props)
  160. rc = reason_code if reason_code is not None else flags_or_rc
  161. rc_val = rc if isinstance(rc, int) else getattr(rc, "value", 0)
  162. if rc_val != 0:
  163. logger.warning("MQTT relay disconnected: %s", rc)
  164. else:
  165. logger.info("MQTT relay disconnected cleanly")
  166. if self._disconnection_event:
  167. self._disconnection_event.set()
  168. async def disconnect(self, timeout: float = 0):
  169. """Disconnect from MQTT broker."""
  170. if self.client:
  171. try:
  172. # Publish offline status before disconnecting
  173. self._publish_status("offline")
  174. self._disconnection_event = threading.Event()
  175. self.client.disconnect()
  176. await asyncio.to_thread(self._disconnection_event.wait, timeout=timeout)
  177. retire_paho_client(self.client, "relay")
  178. except Exception as e:
  179. logger.debug("MQTT disconnect error (ignored): %s", e)
  180. finally:
  181. self.client = None
  182. self.connected = False
  183. def _publish_status(self, status: str):
  184. """Publish BamBuddy status (online/offline)."""
  185. self._publish(
  186. f"{self.topic_prefix}/status",
  187. {"status": status, "timestamp": datetime.now(timezone.utc).isoformat()},
  188. retain=True,
  189. )
  190. def _publish(self, topic: str, payload: dict, retain: bool = False):
  191. """Publish message to MQTT broker."""
  192. if not self.client or not self.connected:
  193. return
  194. try:
  195. with self._lock:
  196. self.client.publish(topic, json.dumps(payload, default=str), qos=1, retain=retain)
  197. except Exception as e:
  198. logger.debug("MQTT publish error: %s", e)
  199. def get_status(self) -> dict:
  200. """Get current MQTT relay status for API."""
  201. return {
  202. "enabled": self.enabled,
  203. "connected": self.connected,
  204. "broker": self._broker if self.enabled else "",
  205. "port": self._port if self.enabled else 0,
  206. "topic_prefix": self.topic_prefix,
  207. }
  208. # =========================================================================
  209. # Printer Events
  210. # =========================================================================
  211. async def on_printer_status(
  212. self,
  213. printer_id: int,
  214. state: Any,
  215. printer_name: str,
  216. printer_serial: str,
  217. awaiting_plate_clear: bool = False,
  218. ):
  219. """Publish printer status change (throttled to 1 update/sec per printer).
  220. A change of ``connected`` is never throttled: the update that says a printer
  221. dropped is retained, and held back it would leave the previous status
  222. standing for as long as the printer stays quiet (#3401).
  223. """
  224. if not self.enabled or not self.connected:
  225. return
  226. # Throttle status updates to avoid flooding MQTT broker
  227. now = time.time()
  228. last_publish = self._last_printer_status.get(printer_id, 0)
  229. last_connected = self._last_printer_connected.get(printer_id)
  230. connected_changed = last_connected is not None and last_connected != state.connected
  231. if not connected_changed and now - last_publish < self.STATUS_THROTTLE_SECONDS:
  232. return # Skip this update, too soon since last publish
  233. self._last_printer_status[printer_id] = now
  234. self._last_printer_connected[printer_id] = state.connected
  235. from backend.app.services.printer_manager import printer_state_to_dict
  236. snapshot = printer_state_to_dict(state, printer_id)
  237. # Build status payload from PrinterState
  238. payload = {
  239. "printer_id": printer_id,
  240. "printer_name": printer_name,
  241. "printer_serial": printer_serial,
  242. "timestamp": datetime.now(timezone.utc).isoformat(),
  243. "connected": state.connected,
  244. "state": state.state,
  245. "progress": state.progress,
  246. "remaining_time": state.remaining_time,
  247. "layer_num": state.layer_num,
  248. "total_layers": state.total_layers,
  249. "current_print": state.current_print,
  250. "subtask_name": state.subtask_name,
  251. "gcode_file": state.gcode_file,
  252. "temperatures": state.temperatures,
  253. "wifi_signal": state.wifi_signal,
  254. "chamber_light": state.chamber_light,
  255. "speed_level": state.speed_level,
  256. "cooling_fan_speed": state.cooling_fan_speed,
  257. "big_fan1_speed": state.big_fan1_speed,
  258. "big_fan2_speed": state.big_fan2_speed,
  259. "heatbreak_fan_speed": state.heatbreak_fan_speed,
  260. "left_aux_fan_speed": state.left_aux_fan_speed,
  261. "exhaust_fan_present": state.exhaust_fan_present,
  262. **{field: snapshot[field] for field in _STATUS_FIELDS_FROM_STATE},
  263. # Bambuddy-side gate, not printer telemetry (#2525). Mirrors what the
  264. # Web UI already receives via printer_state_to_dict, so an external
  265. # automation can tell "finished" from "finished and still waiting for
  266. # someone to clear the bed". Edge changes are also published on
  267. # printers/{serial}/plate_clear — this topic only refreshes when the
  268. # printer pushes telemetry, which stops entirely after Auto Off.
  269. "awaiting_plate_clear": awaiting_plate_clear,
  270. }
  271. self._publish(
  272. f"{self.topic_prefix}/printers/{printer_serial}/status",
  273. payload,
  274. retain=True,
  275. )
  276. async def on_plate_clear_state(
  277. self,
  278. printer_id: int,
  279. printer_name: str,
  280. printer_serial: str,
  281. awaiting: bool,
  282. ):
  283. """Publish the plate-clear gate as it flips (#2525).
  284. Retained, unlike the other per-printer event topics, because this is a
  285. *state* an automation needs on subscribe rather than a moment it might
  286. have missed. The status topic carries the same field, but only refreshes
  287. when the printer pushes telemetry — after Auto Off cycles the printer the
  288. retained status payload would sit at ``awaiting_plate_clear: false``
  289. indefinitely while the gate is in fact still up.
  290. """
  291. if not self.enabled or not self.connected:
  292. return
  293. self._publish(
  294. f"{self.topic_prefix}/printers/{printer_serial}/plate_clear",
  295. {
  296. "printer_id": printer_id,
  297. "printer_name": printer_name,
  298. "printer_serial": printer_serial,
  299. "awaiting": awaiting,
  300. "timestamp": datetime.now(timezone.utc).isoformat(),
  301. },
  302. retain=True,
  303. )
  304. async def on_printer_online(self, printer_id: int, printer_name: str, printer_serial: str):
  305. """Publish printer came online event."""
  306. if not self.enabled or not self.connected:
  307. return
  308. self._publish(
  309. f"{self.topic_prefix}/printers/{printer_serial}/online",
  310. {
  311. "printer_id": printer_id,
  312. "printer_name": printer_name,
  313. "printer_serial": printer_serial,
  314. "timestamp": datetime.now(timezone.utc).isoformat(),
  315. },
  316. )
  317. async def on_printer_offline(self, printer_id: int, printer_name: str, printer_serial: str):
  318. """Publish printer went offline event."""
  319. if not self.enabled or not self.connected:
  320. return
  321. self._publish(
  322. f"{self.topic_prefix}/printers/{printer_serial}/offline",
  323. {
  324. "printer_id": printer_id,
  325. "printer_name": printer_name,
  326. "printer_serial": printer_serial,
  327. "timestamp": datetime.now(timezone.utc).isoformat(),
  328. },
  329. )
  330. async def on_print_start(
  331. self,
  332. printer_id: int,
  333. printer_name: str,
  334. printer_serial: str,
  335. filename: str,
  336. subtask_name: str,
  337. ):
  338. """Publish print started event."""
  339. if not self.enabled or not self.connected:
  340. return
  341. self._publish(
  342. f"{self.topic_prefix}/printers/{printer_serial}/print/started",
  343. {
  344. "printer_id": printer_id,
  345. "printer_name": printer_name,
  346. "printer_serial": printer_serial,
  347. "filename": filename,
  348. "subtask_name": subtask_name,
  349. "timestamp": datetime.now(timezone.utc).isoformat(),
  350. },
  351. )
  352. async def on_print_complete(
  353. self,
  354. printer_id: int,
  355. printer_name: str,
  356. printer_serial: str,
  357. filename: str,
  358. subtask_name: str,
  359. status: str,
  360. ):
  361. """Publish print completed event."""
  362. if not self.enabled or not self.connected:
  363. return
  364. # Determine topic based on status
  365. if status == "completed":
  366. topic = f"{self.topic_prefix}/printers/{printer_serial}/print/completed"
  367. else:
  368. topic = f"{self.topic_prefix}/printers/{printer_serial}/print/failed"
  369. self._publish(
  370. topic,
  371. {
  372. "printer_id": printer_id,
  373. "printer_name": printer_name,
  374. "printer_serial": printer_serial,
  375. "filename": filename,
  376. "subtask_name": subtask_name,
  377. "status": status,
  378. "timestamp": datetime.now(timezone.utc).isoformat(),
  379. },
  380. )
  381. async def on_ams_change(
  382. self,
  383. printer_id: int,
  384. printer_name: str,
  385. printer_serial: str,
  386. ams_data: list,
  387. ):
  388. """Publish AMS filament change event."""
  389. if not self.enabled or not self.connected:
  390. return
  391. self._publish(
  392. f"{self.topic_prefix}/printers/{printer_serial}/ams/changed",
  393. {
  394. "printer_id": printer_id,
  395. "printer_name": printer_name,
  396. "printer_serial": printer_serial,
  397. "ams_units": ams_data,
  398. "timestamp": datetime.now(timezone.utc).isoformat(),
  399. },
  400. )
  401. async def on_printer_error(
  402. self,
  403. printer_id: int,
  404. printer_name: str,
  405. printer_serial: str,
  406. errors: list,
  407. ):
  408. """Publish printer HMS error event."""
  409. if not self.enabled or not self.connected:
  410. return
  411. self._publish(
  412. f"{self.topic_prefix}/printers/{printer_serial}/error",
  413. {
  414. "printer_id": printer_id,
  415. "printer_name": printer_name,
  416. "printer_serial": printer_serial,
  417. "errors": errors,
  418. "timestamp": datetime.now(timezone.utc).isoformat(),
  419. },
  420. )
  421. # =========================================================================
  422. # Print Queue Events
  423. # =========================================================================
  424. async def on_queue_job_added(
  425. self,
  426. job_id: int,
  427. filename: str,
  428. printer_id: int | None,
  429. printer_name: str | None,
  430. ):
  431. """Publish job added to queue event."""
  432. if not self.enabled or not self.connected:
  433. return
  434. self._publish(
  435. f"{self.topic_prefix}/queue/job_added",
  436. {
  437. "job_id": job_id,
  438. "filename": filename,
  439. "printer_id": printer_id,
  440. "printer_name": printer_name,
  441. "timestamp": datetime.now(timezone.utc).isoformat(),
  442. },
  443. )
  444. async def on_queue_job_started(
  445. self,
  446. job_id: int,
  447. filename: str,
  448. printer_id: int,
  449. printer_name: str,
  450. printer_serial: str,
  451. ):
  452. """Publish queued job started printing event."""
  453. if not self.enabled or not self.connected:
  454. return
  455. self._publish(
  456. f"{self.topic_prefix}/queue/job_started",
  457. {
  458. "job_id": job_id,
  459. "filename": filename,
  460. "printer_id": printer_id,
  461. "printer_name": printer_name,
  462. "printer_serial": printer_serial,
  463. "timestamp": datetime.now(timezone.utc).isoformat(),
  464. },
  465. )
  466. async def on_queue_job_completed(
  467. self,
  468. job_id: int,
  469. filename: str,
  470. printer_id: int,
  471. printer_name: str,
  472. status: str,
  473. ):
  474. """Publish queued job finished event."""
  475. if not self.enabled or not self.connected:
  476. return
  477. topic = (
  478. f"{self.topic_prefix}/queue/job_completed"
  479. if status == "completed"
  480. else f"{self.topic_prefix}/queue/job_failed"
  481. )
  482. self._publish(
  483. topic,
  484. {
  485. "job_id": job_id,
  486. "filename": filename,
  487. "printer_id": printer_id,
  488. "printer_name": printer_name,
  489. "status": status,
  490. "timestamp": datetime.now(timezone.utc).isoformat(),
  491. },
  492. )
  493. # =========================================================================
  494. # Maintenance Events
  495. # =========================================================================
  496. async def on_maintenance_alert(
  497. self,
  498. printer_id: int,
  499. printer_name: str,
  500. maintenance_type: str,
  501. current_value: float,
  502. threshold: float,
  503. unit: str,
  504. ):
  505. """Publish that a maintenance item is due or nearly due.
  506. current_value is the hours (or days) since it was last done, threshold
  507. its interval, and unit says which: "hours" or "days".
  508. """
  509. if not self.enabled or not self.connected:
  510. return
  511. self._publish(
  512. f"{self.topic_prefix}/maintenance/alert",
  513. {
  514. "printer_id": printer_id,
  515. "printer_name": printer_name,
  516. "maintenance_type": maintenance_type,
  517. "current_value": current_value,
  518. "threshold": threshold,
  519. "unit": unit,
  520. "timestamp": datetime.now(timezone.utc).isoformat(),
  521. },
  522. )
  523. async def on_maintenance_reset(
  524. self,
  525. printer_id: int,
  526. printer_name: str,
  527. maintenance_type: str,
  528. ):
  529. """Publish maintenance counter reset event."""
  530. if not self.enabled or not self.connected:
  531. return
  532. self._publish(
  533. f"{self.topic_prefix}/maintenance/reset",
  534. {
  535. "printer_id": printer_id,
  536. "printer_name": printer_name,
  537. "maintenance_type": maintenance_type,
  538. "timestamp": datetime.now(timezone.utc).isoformat(),
  539. },
  540. )
  541. # =========================================================================
  542. # Archive Events
  543. # =========================================================================
  544. async def on_archive_created(
  545. self,
  546. archive_id: int,
  547. print_name: str,
  548. printer_name: str,
  549. status: str,
  550. ):
  551. """Publish print archived event."""
  552. if not self.enabled or not self.connected:
  553. return
  554. self._publish(
  555. f"{self.topic_prefix}/archive/created",
  556. {
  557. "archive_id": archive_id,
  558. "print_name": print_name,
  559. "printer_name": printer_name,
  560. "status": status,
  561. "timestamp": datetime.now(timezone.utc).isoformat(),
  562. },
  563. )
  564. async def on_archive_updated(
  565. self,
  566. archive_id: int,
  567. print_name: str,
  568. status: str,
  569. ):
  570. """Publish archive record updated event."""
  571. if not self.enabled or not self.connected:
  572. return
  573. self._publish(
  574. f"{self.topic_prefix}/archive/updated",
  575. {
  576. "archive_id": archive_id,
  577. "print_name": print_name,
  578. "status": status,
  579. "timestamp": datetime.now(timezone.utc).isoformat(),
  580. },
  581. )
  582. # =========================================================================
  583. # Run Events (archive redesign: each print of an archive is a run)
  584. # =========================================================================
  585. @staticmethod
  586. def _run_payload(run, archive, printer_name: str | None) -> dict:
  587. def iso(moment):
  588. # Stored as naive UTC: say so.
  589. if moment is None:
  590. return None
  591. return (moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)).isoformat()
  592. return {
  593. "run_id": run.id,
  594. "archive_id": run.archive_id,
  595. "print_name": run.print_name or (archive.print_name if archive is not None else None),
  596. "printer_id": run.printer_id,
  597. "printer_name": printer_name or run.printer_name,
  598. "plate_id": run.plate_id,
  599. "status": run.status,
  600. "started_at": iso(run.started_at),
  601. "timestamp": datetime.now(timezone.utc).isoformat(),
  602. }
  603. async def on_run_started(self, run, archive, printer_serial: str, printer_name: str | None):
  604. """Publish a print's run opened at its start: the print of an archive,
  605. which the print and archive events above do not name yet."""
  606. if not self.enabled or not self.connected:
  607. return
  608. self._publish(
  609. f"{self.topic_prefix}/printers/{printer_serial}/run/started",
  610. self._run_payload(run, archive, printer_name),
  611. )
  612. async def on_run_completed(self, run, archive, printer_serial: str, printer_name: str | None):
  613. """Publish a print's run as its end wrote it: outcome and figures."""
  614. if not self.enabled or not self.connected:
  615. return
  616. payload = self._run_payload(run, archive, printer_name)
  617. completed_at = run.completed_at
  618. if completed_at is not None and completed_at.tzinfo is None:
  619. completed_at = completed_at.replace(tzinfo=timezone.utc)
  620. payload.update(
  621. {
  622. "completed_at": completed_at.isoformat() if completed_at is not None else None,
  623. "duration_seconds": run.duration_seconds,
  624. # Not measured: an end found at a reconnect, its time the
  625. # estimate or nothing (0).
  626. "duration_unmeasured": bool(run.duration_unmeasured),
  627. "failure_reason": run.failure_reason,
  628. "filament_used_grams": run.filament_used_grams,
  629. "cost": run.cost,
  630. "energy_kwh": run.energy_kwh,
  631. }
  632. )
  633. self._publish(f"{self.topic_prefix}/printers/{printer_serial}/run/completed", payload)
  634. async def on_run_discarded(self, run, printer_serial: str, printer_name: str | None):
  635. """Publish a run dropped without an end: its print ended unseen (a new
  636. print started on the printer) or its archive was deleted. Its id is
  637. gone after this."""
  638. if not self.enabled or not self.connected:
  639. return
  640. self._publish(
  641. f"{self.topic_prefix}/printers/{printer_serial}/run/discarded",
  642. self._run_payload(run, None, printer_name),
  643. )
  644. # =========================================================================
  645. # Filament/Spoolman Events
  646. # =========================================================================
  647. async def on_filament_low(
  648. self,
  649. printer_id: int,
  650. printer_name: str,
  651. printer_serial: str,
  652. slot: str,
  653. remaining_percent: int,
  654. color: str | None,
  655. spool_id: int,
  656. ):
  657. """Publish that the spool in an AMS slot crossed its low-stock threshold.
  658. Sent once per crossing, at the same point as the Low Filament
  659. notification (print_scheduler._emit_filament_low).
  660. """
  661. if not self.enabled or not self.connected:
  662. return
  663. self._publish(
  664. f"{self.topic_prefix}/printers/{printer_serial}/filament/low",
  665. {
  666. "printer_id": printer_id,
  667. "printer_name": printer_name,
  668. "printer_serial": printer_serial,
  669. "slot": slot,
  670. "remaining_percent": remaining_percent,
  671. "color": color,
  672. "spool_id": spool_id,
  673. "timestamp": datetime.now(timezone.utc).isoformat(),
  674. },
  675. )
  676. # =========================================================================
  677. # Smart Plug Events
  678. # =========================================================================
  679. async def on_smart_plug_state(
  680. self,
  681. plug_id: int,
  682. plug_name: str,
  683. state: str,
  684. printer_id: int | None = None,
  685. printer_name: str | None = None,
  686. ):
  687. """Publish smart plug state change event."""
  688. if not self.enabled or not self.connected:
  689. return
  690. topic = f"{self.topic_prefix}/smart_plugs/on" if state == "on" else f"{self.topic_prefix}/smart_plugs/off"
  691. self._publish(
  692. topic,
  693. {
  694. "plug_id": plug_id,
  695. "plug_name": plug_name,
  696. "state": state,
  697. "printer_id": printer_id,
  698. "printer_name": printer_name,
  699. "timestamp": datetime.now(timezone.utc).isoformat(),
  700. },
  701. )
  702. async def on_smart_plug_energy(
  703. self,
  704. plug_id: int,
  705. plug_name: str,
  706. power: float | None,
  707. energy_today: float | None,
  708. energy_total: float | None,
  709. ):
  710. """Publish a plug's power and energy; a value the plug doesn't report is null."""
  711. if not self.enabled or not self.connected:
  712. return
  713. self._publish(
  714. f"{self.topic_prefix}/smart_plugs/energy",
  715. {
  716. "plug_id": plug_id,
  717. "plug_name": plug_name,
  718. "power_watts": power,
  719. "energy_today_kwh": energy_today,
  720. "energy_total_kwh": energy_total,
  721. "timestamp": datetime.now(timezone.utc).isoformat(),
  722. },
  723. )
  724. # Global instance
  725. mqtt_relay = MQTTRelayService()