plug_energy.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """Reading a smart plug's power and state, whatever kind of plug it is."""
  2. from sqlalchemy.ext.asyncio import AsyncSession
  3. from backend.app.models.smart_plug import SmartPlug
  4. from backend.app.services.homeassistant import homeassistant_service
  5. from backend.app.services.mqtt_relay import mqtt_relay
  6. from backend.app.services.rest_smart_plug import rest_smart_plug_service
  7. from backend.app.services.tasmota import tasmota_service
  8. async def _configured_homeassistant(db: AsyncSession):
  9. from backend.app.api.routes.settings import get_homeassistant_settings
  10. ha_settings = await get_homeassistant_settings(db)
  11. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  12. return homeassistant_service
  13. def mqtt_has_lifetime_counter(plug: SmartPlug) -> bool:
  14. """Whether an MQTT plug reads a lifetime counter beside its daily one (#3582)."""
  15. return bool((plug.mqtt_energy_total_path or "").strip())
  16. async def get_plug_energy(plug: SmartPlug, db: AsyncSession) -> dict | None:
  17. """Get energy from plug regardless of type (Tasmota, Home Assistant, MQTT, or REST).
  18. For HA plugs, configures the service with current settings from DB.
  19. For MQTT plugs, returns data from the subscription service.
  20. For REST plugs, polls the status URL with JSON path extraction.
  21. """
  22. if plug.plug_type == "homeassistant":
  23. return await (await _configured_homeassistant(db)).get_energy(plug)
  24. elif plug.plug_type == "mqtt":
  25. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  26. if not mqtt_data:
  27. return None
  28. if mqtt_has_lifetime_counter(plug):
  29. # Per-print energy is the difference of two "total" readings, so it
  30. # must come from the counter that never resets (#3582). None until
  31. # the first message, so the plug is not picked as the counter.
  32. return {
  33. "power": mqtt_data.power,
  34. "today": mqtt_data.energy,
  35. "total": mqtt_data.energy_total,
  36. }
  37. # One energy value and no telling which counter it is: used as both,
  38. # as always. Right for a lifetime counter; a daily one loses a print
  39. # across midnight, which is what the lifetime path is for.
  40. return {
  41. "power": mqtt_data.power,
  42. "today": mqtt_data.energy,
  43. "total": mqtt_data.energy,
  44. }
  45. elif plug.plug_type == "rest":
  46. return await rest_smart_plug_service.get_energy(plug)
  47. else:
  48. return await tasmota_service.get_energy(plug)
  49. async def read_plug(plug: SmartPlug, db: AsyncSession) -> tuple[str | None, float | None]:
  50. """The plug's switch state ("ON", "OFF" or None if unknown) and power in watts.
  51. An unreachable plug reads as (None, None). MQTT plugs answer from the last
  52. message received, without contacting the device.
  53. """
  54. if plug.plug_type == "mqtt":
  55. data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  56. if not data or not mqtt_relay.smart_plug_service.is_reachable(plug.id):
  57. return None, None
  58. return data.state, data.power
  59. if plug.plug_type == "homeassistant":
  60. service = await _configured_homeassistant(db)
  61. elif plug.plug_type == "rest":
  62. service = rest_smart_plug_service
  63. else:
  64. service = tasmota_service
  65. status = await service.get_status(plug)
  66. if not status.get("reachable"):
  67. return None, None
  68. energy = await get_plug_energy(plug, db)
  69. return status.get("state"), (energy or {}).get("power")