mqtt_relay.py 30 KB

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