panda_breath.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. """BIQU Panda Breath chamber heater over MQTT (#1466).
  2. Firmware 1.0.4 added a Home Assistant binding: the device connects to an MQTT
  3. broker and, for a device id ``<id>``, uses
  4. panda_breath/<id>/state JSON document with every value
  5. panda_breath/<id>/availability "online" / "offline"
  6. panda_breath/<id>/command JSON object with the one value to change
  7. The keys and values below are the ones the firmware's own Home Assistant
  8. discovery messages declare (read from the 1.0.4 image): ``work_on`` and
  9. ``drying_running`` are "ON"/"OFF", ``mode`` is one of MODES, ``target_temp``
  10. is 0-60 °C. The device is bound to one printer and reports that printer's
  11. serial number as ``printer_sn``, which is how it is matched to a Bambuddy
  12. printer.
  13. Bambuddy reuses the broker of the MQTT relay settings, like MQTT smart plugs.
  14. """
  15. from __future__ import annotations
  16. import asyncio
  17. import json
  18. import logging
  19. import ssl
  20. import threading
  21. from dataclasses import dataclass
  22. from datetime import datetime, timezone
  23. from typing import Any
  24. import paho.mqtt.client as mqtt
  25. from paho.mqtt.enums import CallbackAPIVersion
  26. from backend.app.utils.paho_teardown import retire_paho_client
  27. logger = logging.getLogger(__name__)
  28. TOPIC_PREFIX = "panda_breath"
  29. MODES = ("auto mode", "power on", "filament drying")
  30. DRYING_MODES = ("pla", "petg", "custom")
  31. MAX_TARGET_TEMP_C = 60
  32. @dataclass
  33. class PandaBreathDevice:
  34. """The last values one device reported."""
  35. device_id: str
  36. online: bool | None = None
  37. chamber_temp: float | None = None
  38. target_temp: float | None = None
  39. work_on: bool | None = None
  40. mode: str | None = None
  41. filament_drying_mode: str | None = None
  42. drying_running: bool | None = None
  43. drying_remaining_min: float | None = None
  44. printer_sn: str | None = None
  45. last_seen: datetime | None = None
  46. def to_dict(self, broker_up: bool = True) -> dict[str, Any]:
  47. """The values the printer card shows (no printer serial number).
  48. Without a broker connection nothing can reach the device and its last
  49. values are stale, so it counts as offline then.
  50. """
  51. return {
  52. "device_id": self.device_id,
  53. "online": self.online if broker_up else False,
  54. "chamber_temp": self.chamber_temp,
  55. "target_temp": self.target_temp,
  56. "work_on": self.work_on,
  57. "mode": self.mode,
  58. "filament_drying_mode": self.filament_drying_mode,
  59. "drying_running": self.drying_running,
  60. "drying_remaining_min": self.drying_remaining_min,
  61. }
  62. def _on_off(value: Any) -> bool | None:
  63. if isinstance(value, bool):
  64. return value
  65. if value is None:
  66. return None
  67. text = str(value).strip().upper()
  68. if text in ("ON", "TRUE", "1"):
  69. return True
  70. if text in ("OFF", "FALSE", "0"):
  71. return False
  72. return None
  73. def _number(value: Any) -> float | None:
  74. if isinstance(value, bool) or value is None:
  75. return None
  76. try:
  77. return float(value)
  78. except (TypeError, ValueError):
  79. return None
  80. def _text(value: Any) -> str | None:
  81. if value is None:
  82. return None
  83. text = str(value).strip()
  84. return text or None
  85. def _same_serial(a: str | None, b: str | None) -> bool:
  86. return bool(a) and bool(b) and a.strip().upper() == b.strip().upper()
  87. class PandaBreathService:
  88. """Follows Panda Breath devices on the shared broker and sends them commands."""
  89. def __init__(self) -> None:
  90. self.client: mqtt.Client | None = None
  91. self.connected = False
  92. self.enabled = False
  93. self.devices: dict[str, PandaBreathDevice] = {}
  94. self._lock = threading.Lock()
  95. self._disconnection_event: threading.Event | None = None
  96. self._broker = ""
  97. self._port = 1883
  98. self._username = ""
  99. self._password = ""
  100. self._use_tls = False
  101. # -- connection -------------------------------------------------------
  102. async def configure(self, settings: dict) -> None:
  103. """Follow the relay's broker while both MQTT and Panda Breath are on."""
  104. enabled = bool(settings.get("mqtt_enabled")) and bool(settings.get("panda_breath_enabled"))
  105. broker = settings.get("mqtt_broker") or ""
  106. if not enabled or not broker:
  107. self.enabled = False
  108. await self.disconnect()
  109. self._forget_devices()
  110. return
  111. port = int(settings.get("mqtt_port") or 1883)
  112. username = settings.get("mqtt_username") or ""
  113. password = settings.get("mqtt_password") or ""
  114. use_tls = bool(settings.get("mqtt_use_tls"))
  115. changed = (broker, port, username, password, use_tls) != (
  116. self._broker,
  117. self._port,
  118. self._username,
  119. self._password,
  120. self._use_tls,
  121. )
  122. self._broker, self._port, self._username, self._password, self._use_tls = (
  123. broker,
  124. port,
  125. username,
  126. password,
  127. use_tls,
  128. )
  129. self.enabled = True
  130. if changed and self.client:
  131. await self.disconnect()
  132. self._forget_devices()
  133. if not self.client:
  134. await self._connect()
  135. def _forget_devices(self) -> None:
  136. """Drop every device and refresh the cards that showed one."""
  137. with self._lock:
  138. serials = {d.printer_sn for d in self.devices.values() if d.printer_sn}
  139. self.devices.clear()
  140. self._broadcast(serials)
  141. def _broadcast(self, serials: set[str]) -> None:
  142. if not serials:
  143. return
  144. from backend.app.services.printer_manager import printer_manager
  145. for serial in serials:
  146. printer_id = printer_manager.printer_id_for_serial(serial)
  147. if printer_id is not None:
  148. printer_manager.schedule_status_broadcast(printer_id)
  149. def _bound_serials(self) -> set[str]:
  150. with self._lock:
  151. return {d.printer_sn for d in self.devices.values() if d.printer_sn}
  152. async def _connect(self) -> None:
  153. try:
  154. client = mqtt.Client(
  155. callback_api_version=CallbackAPIVersion.VERSION2,
  156. client_id=f"bambuddy-pandabreath-{id(self)}",
  157. protocol=mqtt.MQTTv311,
  158. )
  159. client.on_connect = self._on_connect
  160. client.on_disconnect = self._on_disconnect
  161. client.on_message = self._on_message
  162. if self._username:
  163. client.username_pw_set(self._username, self._password)
  164. if self._use_tls:
  165. client.tls_set(cert_reqs=ssl.CERT_NONE)
  166. client.tls_insecure_set(True)
  167. self.client = client
  168. try:
  169. await asyncio.wait_for(
  170. asyncio.to_thread(client.connect_async, self._broker, self._port, 60),
  171. timeout=3.0,
  172. )
  173. except TimeoutError:
  174. logger.warning("Panda Breath: connection to %s:%s timed out", self._broker, self._port)
  175. client.loop_start()
  176. except Exception as e:
  177. logger.error("Panda Breath: MQTT connection failed: %s", e)
  178. self.connected = False
  179. def _on_connect(self, client, userdata, flags, reason_code, properties=None) -> None:
  180. rc = reason_code if isinstance(reason_code, int) else reason_code.value
  181. self.connected = rc == 0
  182. if self.connected:
  183. client.subscribe(f"{TOPIC_PREFIX}/+/state", qos=1)
  184. client.subscribe(f"{TOPIC_PREFIX}/+/availability", qos=1)
  185. logger.info("Panda Breath: listening on %s:%s", self._broker, self._port)
  186. else:
  187. logger.warning("Panda Breath: broker refused the connection: %s", reason_code)
  188. def _on_disconnect(self, client, userdata, flags_or_rc, reason_code=None, properties=None) -> None:
  189. was_connected = self.connected
  190. self.connected = False
  191. if self._disconnection_event:
  192. self._disconnection_event.set()
  193. if was_connected:
  194. # The cards now show their devices offline.
  195. self._broadcast(self._bound_serials())
  196. async def disconnect(self, timeout: float = 0) -> None:
  197. if not self.client:
  198. return
  199. try:
  200. self._disconnection_event = threading.Event()
  201. self.client.disconnect()
  202. await asyncio.to_thread(self._disconnection_event.wait, timeout=timeout)
  203. retire_paho_client(self.client, "panda-breath")
  204. except Exception as e:
  205. logger.debug("Panda Breath disconnect error (ignored): %s", e)
  206. finally:
  207. self.client = None
  208. self.connected = False
  209. # -- incoming ---------------------------------------------------------
  210. def _on_message(self, client, userdata, msg) -> None:
  211. try:
  212. payload = msg.payload.decode("utf-8", errors="replace")
  213. except Exception:
  214. return
  215. printer_ids = self.apply_message(msg.topic or "", payload)
  216. if printer_ids:
  217. from backend.app.services.printer_manager import printer_manager
  218. for printer_id in printer_ids:
  219. printer_manager.schedule_status_broadcast(printer_id)
  220. def apply_message(self, topic: str, payload: str) -> set[int]:
  221. """Take one message in; return the printers whose card changed."""
  222. parts = topic.split("/")
  223. if len(parts) != 3 or parts[0] != TOPIC_PREFIX or not parts[1]:
  224. return set()
  225. device_id, kind = parts[1], parts[2]
  226. with self._lock:
  227. device = self.devices.get(device_id) or PandaBreathDevice(device_id=device_id)
  228. before = (device.to_dict(), device.printer_sn)
  229. if kind == "availability":
  230. device.online = payload.strip().lower() == "online"
  231. elif kind == "state":
  232. try:
  233. data = json.loads(payload)
  234. except json.JSONDecodeError:
  235. return set()
  236. if not isinstance(data, dict):
  237. return set()
  238. self._apply_state(device, data)
  239. device.online = True if device.online is None else device.online
  240. else:
  241. return set()
  242. device.last_seen = datetime.now(timezone.utc)
  243. self.devices[device_id] = device
  244. if (device.to_dict(), device.printer_sn) == before:
  245. return set()
  246. serials = {s for s in (before[1], device.printer_sn) if s}
  247. return {pid for pid in (self._printer_id_for_serial(s) for s in serials) if pid is not None}
  248. @staticmethod
  249. def _apply_state(device: PandaBreathDevice, data: dict) -> None:
  250. if "chamber_temp" in data:
  251. device.chamber_temp = _number(data["chamber_temp"])
  252. if "target_temp" in data:
  253. device.target_temp = _number(data["target_temp"])
  254. if "work_on" in data:
  255. device.work_on = _on_off(data["work_on"])
  256. if "mode" in data:
  257. device.mode = _text(data["mode"])
  258. if "filament_drying_mode" in data:
  259. device.filament_drying_mode = _text(data["filament_drying_mode"])
  260. if "drying_running" in data:
  261. device.drying_running = _on_off(data["drying_running"])
  262. if "drying_remaining_min" in data:
  263. device.drying_remaining_min = _number(data["drying_remaining_min"])
  264. if "printer_sn" in data:
  265. device.printer_sn = _text(data["printer_sn"])
  266. @staticmethod
  267. def _printer_id_for_serial(serial: str) -> int | None:
  268. from backend.app.services.printer_manager import printer_manager
  269. return printer_manager.printer_id_for_serial(serial)
  270. # -- lookups ----------------------------------------------------------
  271. def device_for_serial(self, serial: str | None) -> PandaBreathDevice | None:
  272. """The device bound to the printer with this serial number."""
  273. if not self.enabled or not serial:
  274. return None
  275. with self._lock:
  276. matches = [d for d in self.devices.values() if _same_serial(d.printer_sn, serial)]
  277. if not matches:
  278. return None
  279. # Two devices claiming one printer: the one heard from last.
  280. return max(matches, key=lambda d: d.last_seen or datetime.min.replace(tzinfo=timezone.utc))
  281. def state_for_serial(self, serial: str | None) -> dict[str, Any] | None:
  282. """What the card of the printer with this serial shows, or None."""
  283. device = self.device_for_serial(serial)
  284. return device.to_dict(self.connected) if device else None
  285. def state_for_printer(self, printer_id: int | None) -> dict[str, Any] | None:
  286. """The same for a connected printer, known by id (WebSocket status)."""
  287. if printer_id is None or not self.enabled:
  288. return None
  289. from backend.app.services.printer_manager import printer_manager
  290. info = printer_manager.get_printer(printer_id)
  291. return self.state_for_serial(info.serial_number if info else None)
  292. def get_status(self, printers: dict[str, tuple[int, str]]) -> dict[str, Any]:
  293. """For Settings: the connection and every device heard from.
  294. ``printers`` maps an upper-case serial number to (id, name) for the
  295. printers the caller may see; a device bound to any other printer is
  296. listed without naming it.
  297. """
  298. with self._lock:
  299. devices = list(self.devices.values())
  300. rows = []
  301. for device in sorted(devices, key=lambda d: d.device_id):
  302. printer = printers.get((device.printer_sn or "").strip().upper())
  303. rows.append(
  304. {
  305. **device.to_dict(self.connected),
  306. "bound": bool(device.printer_sn),
  307. "printer_id": printer[0] if printer else None,
  308. "printer_name": printer[1] if printer else None,
  309. }
  310. )
  311. return {"enabled": self.enabled, "connected": self.connected, "devices": rows}
  312. # -- outgoing ---------------------------------------------------------
  313. def send_command(self, device_id: str, key: str, value: Any) -> bool:
  314. """Publish one value change; False when the broker is not reachable."""
  315. if not self.client or not self.connected:
  316. return False
  317. topic = f"{TOPIC_PREFIX}/{device_id}/command"
  318. info = self.client.publish(topic, json.dumps({key: value}), qos=1, retain=False)
  319. return info.rc == mqtt.MQTT_ERR_SUCCESS
  320. panda_breath_service = PandaBreathService()