mqtt_smart_plug.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. """MQTT Smart Plug Service for subscribing to external MQTT topics and extracting power/energy data.
  2. This service enables integration with Shelly, Zigbee2MQTT, and other MQTT-based energy monitoring devices.
  3. """
  4. import asyncio
  5. import json
  6. import logging
  7. import threading
  8. from dataclasses import dataclass, field
  9. from datetime import datetime, timedelta, timezone
  10. from typing import Any
  11. import paho.mqtt.client as mqtt
  12. from backend.app.utils.paho_teardown import retire_paho_client
  13. logger = logging.getLogger(__name__)
  14. @dataclass
  15. class SmartPlugMQTTData:
  16. """Latest data received from an MQTT smart plug."""
  17. plug_id: int
  18. power: float | None = None # Current power in watts
  19. energy: float | None = None # Energy in kWh (today)
  20. state: str | None = None # "ON" or "OFF"
  21. last_seen: datetime = field(default_factory=datetime.utcnow)
  22. @dataclass
  23. class MQTTDataSourceConfig:
  24. """Configuration for a single MQTT data source (power, energy, or state)."""
  25. topic: str
  26. path: str
  27. multiplier: float = 1.0 # For power/energy
  28. on_value: str | None = None # For state (what value means "ON")
  29. class MQTTSmartPlugService:
  30. """Subscribes to MQTT topics for smart plug energy monitoring."""
  31. # Consider plug unreachable if no message received in this time
  32. REACHABLE_TIMEOUT_MINUTES = 5
  33. def __init__(self):
  34. self.client: mqtt.Client | None = None
  35. self.connected = False
  36. self._lock = threading.Lock()
  37. # topic -> list of (plug_id, data_type) where data_type is "power", "energy", or "state"
  38. self.subscriptions: dict[str, list[tuple[int, str]]] = {}
  39. # plug_id -> {data_type: MQTTDataSourceConfig}
  40. self.plug_configs: dict[int, dict[str, MQTTDataSourceConfig]] = {}
  41. # plug_id -> latest data
  42. self.plug_data: dict[int, SmartPlugMQTTData] = {}
  43. self._disconnection_event: threading.Event | None = None
  44. self._configured = False
  45. self._broker = ""
  46. self._port = 1883
  47. self._username = ""
  48. self._password = ""
  49. self._use_tls = False
  50. def is_configured(self) -> bool:
  51. """Check if the MQTT service is configured and connected."""
  52. return self._configured and self.connected
  53. def has_broker_settings(self) -> bool:
  54. """Check if broker settings are available (even if not connected yet)."""
  55. return bool(self._broker)
  56. async def configure(self, settings: dict) -> bool:
  57. """Configure MQTT connection from settings.
  58. Uses the same broker settings as the MQTT relay service.
  59. Returns True if connection was successful or MQTT is disabled.
  60. """
  61. enabled = settings.get("mqtt_enabled", False)
  62. if not enabled:
  63. await self.disconnect()
  64. self._configured = False
  65. logger.debug("MQTT smart plug service disabled (MQTT relay not enabled)")
  66. return True
  67. broker = settings.get("mqtt_broker", "")
  68. port = settings.get("mqtt_port", 1883)
  69. username = settings.get("mqtt_username", "")
  70. password = settings.get("mqtt_password", "")
  71. use_tls = settings.get("mqtt_use_tls", False)
  72. if not broker:
  73. logger.warning("MQTT smart plug service: no broker configured")
  74. self._configured = False
  75. return False
  76. # Check if settings changed
  77. settings_changed = (
  78. self._broker != broker
  79. or self._port != port
  80. or self._username != username
  81. or self._password != password
  82. or self._use_tls != use_tls
  83. )
  84. self._broker = broker
  85. self._port = port
  86. self._username = username
  87. self._password = password
  88. self._use_tls = use_tls
  89. self._configured = True
  90. # Disconnect and reconnect if settings changed
  91. if settings_changed and self.client:
  92. await self.disconnect()
  93. # Connect if not already connected
  94. if not self.client or not self.connected:
  95. return await self._connect()
  96. return True
  97. async def _connect(self) -> bool:
  98. """Establish MQTT connection."""
  99. import asyncio
  100. import ssl
  101. try:
  102. # Create client with callback API version 2
  103. self.client = mqtt.Client(
  104. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  105. client_id=f"bambuddy-smartplug-{id(self)}",
  106. protocol=mqtt.MQTTv311,
  107. )
  108. # Set up callbacks
  109. self.client.on_connect = self._on_connect
  110. self.client.on_disconnect = self._on_disconnect
  111. self.client.on_message = self._on_message
  112. # Configure authentication
  113. if self._username:
  114. self.client.username_pw_set(self._username, self._password)
  115. # Configure TLS
  116. if self._use_tls:
  117. self.client.tls_set(cert_reqs=ssl.CERT_NONE)
  118. self.client.tls_insecure_set(True)
  119. # Connect with timeout
  120. try:
  121. await asyncio.wait_for(
  122. asyncio.to_thread(self.client.connect_async, self._broker, self._port, 60),
  123. timeout=3.0,
  124. )
  125. except TimeoutError:
  126. logger.warning("MQTT smart plug connection to %s:%s timed out", self._broker, self._port)
  127. return False
  128. self.client.loop_start()
  129. # Wait briefly for connection
  130. await asyncio.sleep(1.0)
  131. if self.connected:
  132. logger.info("MQTT smart plug service connected to %s:%s", self._broker, self._port)
  133. # Resubscribe to all topics
  134. self._resubscribe_all()
  135. return True
  136. else:
  137. logger.warning("MQTT smart plug connection pending to %s:%s", self._broker, self._port)
  138. return True # Connection is async
  139. except Exception as e:
  140. logger.error("MQTT smart plug connection failed: %s", e)
  141. self.connected = False
  142. return False
  143. def _on_connect(
  144. self,
  145. client: mqtt.Client,
  146. userdata: Any,
  147. flags: dict,
  148. reason_code: int | mqtt.ReasonCode,
  149. properties: mqtt.Properties | None = None,
  150. ):
  151. """Callback when connected to broker."""
  152. rc = reason_code if isinstance(reason_code, int) else reason_code.value
  153. if rc == 0:
  154. self.connected = True
  155. logger.info("MQTT smart plug service connected successfully")
  156. # Resubscribe to all topics
  157. self._resubscribe_all()
  158. else:
  159. self.connected = False
  160. logger.error("MQTT smart plug connection failed: %s", reason_code)
  161. def _on_disconnect(
  162. self,
  163. client: mqtt.Client,
  164. userdata: Any,
  165. flags_or_rc: dict | int | mqtt.ReasonCode,
  166. reason_code: int | mqtt.ReasonCode | None = None,
  167. properties: mqtt.Properties | None = None,
  168. ):
  169. """Callback when disconnected from broker."""
  170. self.connected = False
  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 smart plug service disconnected: %s", rc)
  175. else:
  176. logger.info("MQTT smart plug service disconnected cleanly")
  177. if self._disconnection_event:
  178. self._disconnection_event.set()
  179. def _on_message(self, client: mqtt.Client, userdata: Any, msg: mqtt.MQTTMessage):
  180. """Handle incoming MQTT message, extract data using JSON path."""
  181. topic = msg.topic
  182. with self._lock:
  183. subscriptions = self.subscriptions.get(topic, [])
  184. if not subscriptions:
  185. return
  186. # Parse JSON payload (or treat as raw value)
  187. try:
  188. payload = json.loads(msg.payload.decode("utf-8"))
  189. is_json = True
  190. except (json.JSONDecodeError, UnicodeDecodeError):
  191. # Not JSON - treat the whole payload as a raw value
  192. payload = msg.payload.decode("utf-8").strip()
  193. is_json = False
  194. # Process for each subscribed (plug_id, data_type)
  195. for plug_id, data_type in subscriptions:
  196. configs = self.plug_configs.get(plug_id, {})
  197. config = configs.get(data_type)
  198. if not config:
  199. continue
  200. # Extract value using path (or use raw payload if no path)
  201. if is_json and config.path:
  202. raw_value = self._extract_json_path(payload, config.path)
  203. elif is_json and not config.path:
  204. # JSON but no path - if it's a simple value use it, otherwise skip
  205. if isinstance(payload, (int, float, str, bool)):
  206. raw_value = payload
  207. else:
  208. # Can't use a dict/list as a value
  209. logger.debug("MQTT plug %s: JSON payload is object/array but no path configured", plug_id)
  210. continue
  211. else:
  212. # Raw value (non-JSON)
  213. raw_value = payload
  214. if raw_value is None:
  215. continue
  216. # Initialize plug data if needed
  217. if plug_id not in self.plug_data:
  218. self.plug_data[plug_id] = SmartPlugMQTTData(plug_id=plug_id)
  219. data = self.plug_data[plug_id]
  220. data.last_seen = datetime.now(timezone.utc)
  221. # Process based on data type
  222. if data_type == "power":
  223. try:
  224. data.power = float(raw_value) * config.multiplier
  225. logger.debug("MQTT smart plug %s: power=%s", plug_id, data.power)
  226. except (ValueError, TypeError):
  227. pass # Ignore unparseable power reading from MQTT
  228. elif data_type == "energy":
  229. try:
  230. data.energy = float(raw_value) * config.multiplier
  231. logger.debug("MQTT smart plug %s: energy=%s", plug_id, data.energy)
  232. except (ValueError, TypeError):
  233. pass # Ignore unparseable energy reading from MQTT
  234. elif data_type == "state":
  235. state_str = str(raw_value)
  236. # Check against configured ON value if set
  237. if config.on_value:
  238. # Case-insensitive comparison
  239. if state_str.lower() == config.on_value.lower():
  240. data.state = "ON"
  241. else:
  242. data.state = "OFF"
  243. else:
  244. # Default behavior: normalize common values
  245. upper_state = state_str.upper()
  246. if upper_state in ("ON", "1", "TRUE"):
  247. data.state = "ON"
  248. elif upper_state in ("OFF", "0", "FALSE"):
  249. data.state = "OFF"
  250. else:
  251. data.state = state_str
  252. logger.debug("MQTT smart plug %s: state=%s", plug_id, data.state)
  253. def _extract_json_path(self, data: dict, path: str) -> Any:
  254. """Extract value using dot notation (e.g., 'power_l1' or 'data.power').
  255. Supports simple dot notation for nested objects.
  256. """
  257. if not path:
  258. return None
  259. parts = path.split(".")
  260. current = data
  261. for part in parts:
  262. if isinstance(current, dict) and part in current:
  263. current = current[part]
  264. else:
  265. return None
  266. return current
  267. def _resubscribe_all(self):
  268. """Resubscribe to all registered topics after reconnection."""
  269. if not self.client or not self.connected:
  270. return
  271. with self._lock:
  272. for topic in self.subscriptions:
  273. if self.subscriptions[topic]: # Only if there are subscribers
  274. try:
  275. self.client.subscribe(topic, qos=1)
  276. logger.debug("MQTT smart plug: resubscribed to %s", topic)
  277. except Exception as e:
  278. logger.error("MQTT smart plug: failed to resubscribe to %s: %s", topic, e)
  279. def subscribe(
  280. self,
  281. plug_id: int,
  282. # Power source
  283. power_topic: str | None = None,
  284. power_path: str | None = None,
  285. power_multiplier: float = 1.0,
  286. # Energy source
  287. energy_topic: str | None = None,
  288. energy_path: str | None = None,
  289. energy_multiplier: float = 1.0,
  290. # State source
  291. state_topic: str | None = None,
  292. state_path: str | None = None,
  293. state_on_value: str | None = None,
  294. # Legacy: single topic/path/multiplier (for backward compatibility)
  295. topic: str | None = None,
  296. multiplier: float = 1.0,
  297. ):
  298. """Subscribe to MQTT topics for a plug.
  299. Each data type (power, energy, state) can have its own topic.
  300. For backward compatibility, if power_topic is not set but topic is,
  301. topic will be used for all data types that have paths configured.
  302. """
  303. with self._lock:
  304. # Initialize config for this plug
  305. self.plug_configs[plug_id] = {}
  306. # Determine topics (new fields take priority, fall back to legacy)
  307. effective_power_topic = power_topic or topic
  308. effective_energy_topic = energy_topic or topic
  309. effective_state_topic = state_topic or topic
  310. # Use new multipliers or fall back to legacy
  311. effective_power_mult = power_multiplier if power_multiplier != 1.0 else multiplier
  312. effective_energy_mult = energy_multiplier if energy_multiplier != 1.0 else multiplier
  313. # Configure power subscription (path is optional - empty means use raw payload)
  314. if effective_power_topic:
  315. config = MQTTDataSourceConfig(
  316. topic=effective_power_topic,
  317. path=power_path or "",
  318. multiplier=effective_power_mult,
  319. )
  320. self.plug_configs[plug_id]["power"] = config
  321. self._add_subscription(plug_id, effective_power_topic, "power")
  322. # Configure energy subscription (path is optional - empty means use raw payload)
  323. if effective_energy_topic:
  324. config = MQTTDataSourceConfig(
  325. topic=effective_energy_topic,
  326. path=energy_path or "",
  327. multiplier=effective_energy_mult,
  328. )
  329. self.plug_configs[plug_id]["energy"] = config
  330. self._add_subscription(plug_id, effective_energy_topic, "energy")
  331. # Configure state subscription (path is optional - empty means use raw payload)
  332. if effective_state_topic:
  333. config = MQTTDataSourceConfig(
  334. topic=effective_state_topic,
  335. path=state_path or "",
  336. on_value=state_on_value,
  337. )
  338. self.plug_configs[plug_id]["state"] = config
  339. self._add_subscription(plug_id, effective_state_topic, "state")
  340. # Initialize data entry
  341. if plug_id not in self.plug_data:
  342. self.plug_data[plug_id] = SmartPlugMQTTData(plug_id=plug_id)
  343. logger.info(
  344. f"MQTT smart plug {plug_id}: configured with "
  345. f"power={effective_power_topic if power_path else None}, "
  346. f"energy={effective_energy_topic if energy_path else None}, "
  347. f"state={effective_state_topic if state_path else None}"
  348. )
  349. def _add_subscription(self, plug_id: int, topic: str, data_type: str):
  350. """Add a subscription for a plug/data_type to a topic."""
  351. if topic not in self.subscriptions:
  352. self.subscriptions[topic] = []
  353. # Actually subscribe if connected
  354. if self.client and self.connected:
  355. try:
  356. self.client.subscribe(topic, qos=1)
  357. logger.info("MQTT smart plug: subscribed to %s", topic)
  358. except Exception as e:
  359. logger.error("MQTT smart plug: failed to subscribe to %s: %s", topic, e)
  360. entry = (plug_id, data_type)
  361. if entry not in self.subscriptions[topic]:
  362. self.subscriptions[topic].append(entry)
  363. def unsubscribe(self, plug_id: int):
  364. """Unsubscribe when plug is deleted/updated."""
  365. with self._lock:
  366. # Get all configs for this plug
  367. configs = self.plug_configs.pop(plug_id, {})
  368. if not configs:
  369. # Still clean up any stray subscriptions
  370. pass
  371. # Collect all topics this plug was subscribed to
  372. topics_to_check = set()
  373. for _data_type, config in configs.items():
  374. topics_to_check.add(config.topic)
  375. # Also scan subscriptions to remove any entries for this plug
  376. for topic in list(self.subscriptions.keys()):
  377. # Remove all entries for this plug_id
  378. self.subscriptions[topic] = [(pid, dtype) for pid, dtype in self.subscriptions[topic] if pid != plug_id]
  379. topics_to_check.add(topic)
  380. # Unsubscribe from topics with no more subscribers
  381. for topic in topics_to_check:
  382. if topic in self.subscriptions and not self.subscriptions[topic]:
  383. del self.subscriptions[topic]
  384. if self.client and self.connected:
  385. try:
  386. self.client.unsubscribe(topic)
  387. logger.info("MQTT smart plug: unsubscribed from %s", topic)
  388. except Exception as e:
  389. logger.error("MQTT smart plug: failed to unsubscribe from %s: %s", topic, e)
  390. # Remove data
  391. self.plug_data.pop(plug_id, None)
  392. def get_plug_data(self, plug_id: int) -> SmartPlugMQTTData | None:
  393. """Get latest data for a plug (called by status endpoint)."""
  394. with self._lock:
  395. return self.plug_data.get(plug_id)
  396. def is_reachable(self, plug_id: int) -> bool:
  397. """Check if a plug has received data recently."""
  398. data = self.get_plug_data(plug_id)
  399. if not data:
  400. return False
  401. timeout = timedelta(minutes=self.REACHABLE_TIMEOUT_MINUTES)
  402. return datetime.now(timezone.utc) - data.last_seen < timeout
  403. async def disconnect(self, timeout: float = 0):
  404. """Disconnect from MQTT broker."""
  405. if self.client:
  406. try:
  407. self._disconnection_event = threading.Event()
  408. self.client.disconnect()
  409. await asyncio.to_thread(self._disconnection_event.wait, timeout=timeout)
  410. retire_paho_client(self.client, "smart-plugs")
  411. except Exception as e:
  412. logger.debug("MQTT smart plug disconnect error (ignored): %s", e)
  413. finally:
  414. self.client = None
  415. self.connected = False
  416. def subscribe_plug_to_mqtt(service: "MQTTSmartPlugService", plug: Any) -> list[str]:
  417. """Resolve per-type topic fields on a SmartPlug and register it with the service.
  418. The SmartPlug model carries both a legacy single `mqtt_topic` and newer
  419. per-type `mqtt_{power,energy,state}_topic` fields. Three code paths used
  420. to open-code this resolution (startup restore, create, update) and they
  421. drifted — the startup path skipped plugs that only had per-type topics
  422. set, leaving them unsubscribed after every restart (#1010). Funnelling
  423. all three through this helper keeps them in sync.
  424. Returns the list of topics subscribed (empty if nothing was configured).
  425. """
  426. power_topic = plug.mqtt_power_topic or plug.mqtt_topic
  427. energy_topic = plug.mqtt_energy_topic or plug.mqtt_topic
  428. state_topic = plug.mqtt_state_topic or plug.mqtt_topic
  429. if not (power_topic or energy_topic or state_topic):
  430. return []
  431. legacy_mult = plug.mqtt_multiplier or 1.0
  432. service.subscribe(
  433. plug_id=plug.id,
  434. power_topic=power_topic,
  435. power_path=plug.mqtt_power_path,
  436. power_multiplier=plug.mqtt_power_multiplier or legacy_mult,
  437. energy_topic=energy_topic,
  438. energy_path=plug.mqtt_energy_path,
  439. energy_multiplier=plug.mqtt_energy_multiplier or legacy_mult,
  440. state_topic=state_topic,
  441. state_path=plug.mqtt_state_path,
  442. state_on_value=plug.mqtt_state_on_value,
  443. )
  444. return [t for t in {power_topic, energy_topic, state_topic} if t]
  445. # Global instance
  446. mqtt_smart_plug_service = MQTTSmartPlugService()