smart_plug.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. from datetime import datetime
  2. from typing import Literal
  3. from pydantic import BaseModel, Field, field_validator, model_validator
  4. from backend.app.schemas.not_null import IgnoresNullForRequiredColumns
  5. from backend.app.services.secret_fields import SECRET_PLACEHOLDER
  6. # A REST plug's URLs and request bodies, shown only to those who may edit plugs.
  7. REST_EDITOR_FIELDS = (
  8. "rest_on_url",
  9. "rest_off_url",
  10. "rest_status_url",
  11. "rest_power_url",
  12. "rest_energy_url",
  13. "rest_on_body",
  14. "rest_off_body",
  15. )
  16. class SmartPlugBase(BaseModel):
  17. name: str = Field(..., min_length=1, max_length=100)
  18. plug_type: Literal["tasmota", "homeassistant", "mqtt", "rest"] = "tasmota"
  19. # Tasmota fields (required when plug_type="tasmota")
  20. ip_address: str | None = Field(default=None, pattern=r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
  21. username: str | None = None
  22. password: str | None = None
  23. # Home Assistant fields (required when plug_type="homeassistant")
  24. ha_entity_id: str | None = Field(default=None, pattern=r"^(switch|light|input_boolean|script)\.[a-z0-9_]+$")
  25. # Home Assistant energy sensor entities (optional, for separate energy sensors)
  26. ha_power_entity: str | None = Field(default=None, pattern=r"^sensor\.[a-z0-9_]+$")
  27. ha_energy_today_entity: str | None = Field(default=None, pattern=r"^sensor\.[a-z0-9_]+$")
  28. ha_energy_total_entity: str | None = Field(default=None, pattern=r"^sensor\.[a-z0-9_]+$")
  29. # MQTT fields (required when plug_type="mqtt")
  30. # Legacy field - kept for backward compatibility
  31. mqtt_topic: str | None = Field(default=None, max_length=200) # Deprecated, use mqtt_power_topic
  32. # Power monitoring
  33. mqtt_power_topic: str | None = Field(default=None, max_length=200) # Topic for power data
  34. mqtt_power_path: str | None = Field(default=None, max_length=100) # e.g., "power_l1" or "data.power"
  35. mqtt_power_multiplier: float = Field(default=1.0, gt=0, le=10000) # Unit conversion for power
  36. # Energy monitoring
  37. mqtt_energy_topic: str | None = Field(default=None, max_length=200) # Topic for energy data
  38. mqtt_energy_path: str | None = Field(default=None, max_length=100) # e.g., "energy_l1"
  39. mqtt_energy_multiplier: float = Field(default=1.0, gt=0, le=10000) # Unit conversion for energy
  40. # Lifetime counter on the energy topic that never resets (#3582), e.g.
  41. # Tasmota's ENERGY.Total. Per-print energy reads it when set.
  42. mqtt_energy_total_path: str | None = Field(default=None, max_length=100)
  43. mqtt_energy_total_multiplier: float = Field(default=1.0, gt=0, le=10000)
  44. # State monitoring
  45. mqtt_state_topic: str | None = Field(default=None, max_length=200) # Topic for state data
  46. mqtt_state_path: str | None = Field(default=None, max_length=100) # e.g., "state_l1" for ON/OFF
  47. mqtt_state_on_value: str | None = Field(
  48. default=None, max_length=50
  49. ) # What value means "ON" (e.g., "ON", "true", "1")
  50. # Legacy multiplier - kept for backward compatibility
  51. mqtt_multiplier: float = Field(default=1.0, gt=0, le=10000) # Deprecated, use mqtt_power_multiplier
  52. # REST/Webhook fields (required when plug_type="rest")
  53. rest_on_url: str | None = Field(default=None, max_length=500)
  54. rest_on_body: str | None = None
  55. rest_off_url: str | None = Field(default=None, max_length=500)
  56. rest_off_body: str | None = None
  57. rest_method: Literal["GET", "POST", "PUT", "PATCH"] | None = None
  58. rest_headers: str | None = None # JSON string of custom headers
  59. rest_status_url: str | None = Field(default=None, max_length=500)
  60. rest_status_path: str | None = Field(default=None, max_length=200)
  61. rest_status_on_value: str | None = Field(default=None, max_length=50)
  62. rest_power_url: str | None = Field(default=None, max_length=500)
  63. rest_power_path: str | None = Field(default=None, max_length=200)
  64. rest_power_multiplier: float = Field(default=1.0, gt=0, le=10000)
  65. rest_energy_url: str | None = Field(default=None, max_length=500)
  66. # Today's usage, resetting at midnight.
  67. rest_energy_path: str | None = Field(default=None, max_length=200)
  68. rest_energy_multiplier: float = Field(default=1.0, gt=0, le=10000)
  69. # Lifetime counter that never resets (#2539) — a Shelly's `aenergy.total`.
  70. rest_energy_total_path: str | None = Field(default=None, max_length=200)
  71. rest_energy_total_multiplier: float = Field(default=1.0, gt=0, le=10000)
  72. printer_id: int | None = None
  73. # #2629: only a plug that really feeds the printer may mark it offline when
  74. # it switches off. Accessory plugs (filter fan, lights) are linked to a
  75. # printer purely to follow the print cycle.
  76. controls_printer_power: bool = True
  77. enabled: bool = True
  78. auto_on: bool = True
  79. auto_off: bool = True
  80. auto_off_persistent: bool = False
  81. off_delay_mode: Literal["time", "temperature"] = "time"
  82. off_delay_minutes: int = Field(default=5, ge=0, le=60)
  83. off_temp_threshold: int = Field(default=70, ge=30, le=150)
  84. # #1349: auto-off after AMS drying completes. Independent of `auto_off`
  85. # (print-finish). Fires whenever any AMS on the linked printer finishes
  86. # a dry cycle.
  87. auto_off_after_drying: bool = False
  88. off_delay_after_drying_minutes: int = Field(default=10, ge=0, le=120)
  89. # Power alerts
  90. power_alert_enabled: bool = False
  91. power_alert_high: float | None = Field(default=None, ge=0, le=5000) # Alert when power > this (watts)
  92. power_alert_low: float | None = Field(default=None, ge=0, le=5000) # Alert when power < this (watts)
  93. # Schedule
  94. schedule_enabled: bool = False
  95. schedule_on_time: str | None = Field(default=None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$") # HH:MM format
  96. schedule_off_time: str | None = Field(default=None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$") # HH:MM format
  97. # Visibility options
  98. show_in_switchbar: bool = False
  99. show_on_printer_card: bool = True # For scripts: show on printer card
  100. @model_validator(mode="after")
  101. def validate_plug_type_fields(self) -> "SmartPlugBase":
  102. if self.plug_type == "tasmota" and not self.ip_address:
  103. raise ValueError("ip_address is required for Tasmota plugs")
  104. if self.plug_type == "homeassistant" and not self.ha_entity_id:
  105. raise ValueError("ha_entity_id is required for Home Assistant plugs")
  106. if self.plug_type == "mqtt":
  107. # Determine the effective power topic (new field takes priority, fall back to legacy)
  108. power_topic = self.mqtt_power_topic or self.mqtt_topic
  109. # Path is optional - if not set, raw MQTT payload value will be used
  110. has_power = bool(power_topic)
  111. has_energy = bool(self.mqtt_energy_topic)
  112. has_state = bool(self.mqtt_state_topic)
  113. # At least one data source must be configured (path is optional)
  114. if not has_power and not has_energy and not has_state:
  115. raise ValueError("At least one MQTT topic must be configured for power, energy, or state monitoring")
  116. # The lifetime counter is read from the energy topic's JSON.
  117. if (self.mqtt_energy_total_path or "").strip() and not (self.mqtt_energy_topic or self.mqtt_topic):
  118. raise ValueError("The lifetime energy path needs an energy topic")
  119. if self.plug_type == "rest":
  120. if not self.rest_on_url and not self.rest_off_url:
  121. raise ValueError("At least one of ON URL or OFF URL is required for REST plugs")
  122. return self
  123. class SmartPlugCreate(SmartPlugBase):
  124. pass
  125. class SmartPlugUpdate(IgnoresNullForRequiredColumns):
  126. __orm_table__ = "smart_plugs"
  127. name: str | None = None
  128. plug_type: Literal["tasmota", "homeassistant", "mqtt", "rest"] | None = None
  129. ip_address: str | None = None
  130. ha_entity_id: str | None = None
  131. # Home Assistant energy sensor entities (optional)
  132. ha_power_entity: str | None = None
  133. ha_energy_today_entity: str | None = None
  134. ha_energy_total_entity: str | None = None
  135. # MQTT fields (legacy)
  136. mqtt_topic: str | None = None
  137. mqtt_multiplier: float | None = Field(default=None, gt=0, le=10000)
  138. # MQTT power fields
  139. mqtt_power_topic: str | None = None
  140. mqtt_power_path: str | None = None
  141. mqtt_power_multiplier: float | None = Field(default=None, gt=0, le=10000)
  142. # MQTT energy fields
  143. mqtt_energy_topic: str | None = None
  144. mqtt_energy_path: str | None = None
  145. mqtt_energy_multiplier: float | None = Field(default=None, gt=0, le=10000)
  146. mqtt_energy_total_path: str | None = None
  147. mqtt_energy_total_multiplier: float | None = Field(default=None, gt=0, le=10000)
  148. # MQTT state fields
  149. mqtt_state_topic: str | None = None
  150. mqtt_state_path: str | None = None
  151. mqtt_state_on_value: str | None = None
  152. # REST fields
  153. rest_on_url: str | None = None
  154. rest_on_body: str | None = None
  155. rest_off_url: str | None = None
  156. rest_off_body: str | None = None
  157. rest_method: Literal["GET", "POST", "PUT", "PATCH"] | None = None
  158. rest_headers: str | None = None
  159. rest_status_url: str | None = None
  160. rest_status_path: str | None = None
  161. rest_status_on_value: str | None = None
  162. rest_power_url: str | None = None
  163. rest_power_path: str | None = None
  164. rest_power_multiplier: float | None = Field(default=None, gt=0, le=10000)
  165. rest_energy_url: str | None = None
  166. rest_energy_path: str | None = None
  167. rest_energy_multiplier: float | None = Field(default=None, gt=0, le=10000)
  168. rest_energy_total_path: str | None = None
  169. rest_energy_total_multiplier: float | None = Field(default=None, gt=0, le=10000)
  170. printer_id: int | None = None
  171. # #2629: see SmartPlugBase.controls_printer_power.
  172. controls_printer_power: bool | None = None
  173. enabled: bool | None = None
  174. auto_on: bool | None = None
  175. auto_off: bool | None = None
  176. auto_off_persistent: bool | None = None
  177. off_delay_mode: Literal["time", "temperature"] | None = None
  178. off_delay_minutes: int | None = Field(default=None, ge=0, le=60)
  179. off_temp_threshold: int | None = Field(default=None, ge=30, le=150)
  180. # #1349: per-plug drying auto-off.
  181. auto_off_after_drying: bool | None = None
  182. off_delay_after_drying_minutes: int | None = Field(default=None, ge=0, le=120)
  183. username: str | None = None
  184. password: str | None = None
  185. # Power alerts
  186. power_alert_enabled: bool | None = None
  187. power_alert_high: float | None = Field(default=None, ge=0, le=5000)
  188. power_alert_low: float | None = Field(default=None, ge=0, le=5000)
  189. # Schedule
  190. schedule_enabled: bool | None = None
  191. schedule_on_time: str | None = Field(default=None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$")
  192. schedule_off_time: str | None = Field(default=None, pattern=r"^([01]\d|2[0-3]):[0-5]\d$")
  193. # Visibility options
  194. show_in_switchbar: bool | None = None
  195. show_on_printer_card: bool | None = None
  196. class SmartPlugResponse(SmartPlugBase):
  197. id: int
  198. last_state: str | None = None
  199. last_checked: datetime | None = None
  200. auto_off_executed: bool = False # True when auto-off was triggered after print
  201. power_alert_last_triggered: datetime | None = None
  202. created_at: datetime
  203. updated_at: datetime
  204. class Config:
  205. from_attributes = True
  206. @field_validator("password", "rest_headers", mode="after")
  207. @classmethod
  208. def _write_only(cls, value: str | None) -> str | None:
  209. """Secrets are write-only: a set one is shown as the placeholder."""
  210. return SECRET_PLACEHOLDER if value else value
  211. @model_validator(mode="after")
  212. def _rest_for_editors(self) -> "SmartPlugResponse":
  213. """Readers get no REST URLs or bodies: they commonly carry the device's
  214. credential, and a plug is switched and polled by its id. After the
  215. base checks, which need them."""
  216. for field in REST_EDITOR_FIELDS:
  217. setattr(self, field, None)
  218. return self
  219. class SmartPlugResponseWithSecret(SmartPlugResponse):
  220. """SmartPlugResponse with the REST URLs and bodies. Returned only to callers
  221. who may edit plugs (or with authentication off)."""
  222. @model_validator(mode="after")
  223. def _rest_for_editors(self) -> "SmartPlugResponseWithSecret":
  224. """Editors keep them, to edit them."""
  225. return self
  226. class SmartPlugControl(BaseModel):
  227. action: Literal["on", "off", "toggle"]
  228. class SmartPlugEnergy(BaseModel):
  229. """Energy monitoring data from a smart plug."""
  230. power: float | None = None # Current watts
  231. voltage: float | None = None # Volts
  232. current: float | None = None # Amps
  233. today: float | None = None # kWh used today
  234. yesterday: float | None = None # kWh used yesterday
  235. total: float | None = None # Total kWh
  236. factor: float | None = None # Power factor (0-1)
  237. apparent_power: float | None = None # VA
  238. reactive_power: float | None = None # VAr
  239. class SmartPlugStatus(BaseModel):
  240. state: str | None = None # "ON", "OFF", or None if unreachable
  241. reachable: bool = True
  242. device_name: str | None = None
  243. energy: SmartPlugEnergy | None = None # Energy data if available
  244. class SmartPlugTestConnection(BaseModel):
  245. ip_address: str = Field(..., pattern=r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
  246. username: str | None = None
  247. password: str | None = None
  248. # The saved plug being edited: its stored password fills in the placeholder.
  249. plug_id: int | None = None
  250. # Home Assistant schemas
  251. class HATestConnectionRequest(BaseModel):
  252. """Request to test Home Assistant connection."""
  253. url: str = Field(..., min_length=1)
  254. token: str = Field(..., min_length=1)
  255. class HATestConnectionResponse(BaseModel):
  256. """Response from HA connection test."""
  257. success: bool
  258. message: str | None = None
  259. error: str | None = None
  260. class HAEntity(BaseModel):
  261. """A Home Assistant entity that can be used as a smart plug."""
  262. entity_id: str
  263. friendly_name: str
  264. state: str | None = None
  265. domain: str # "switch", "light", "input_boolean", "script"
  266. class HASensorEntity(BaseModel):
  267. """A Home Assistant sensor entity for energy monitoring."""
  268. entity_id: str
  269. friendly_name: str
  270. state: str | None = None
  271. unit_of_measurement: str | None = None # "W", "kW", "kWh", "Wh"
  272. class RESTTestConnectionRequest(BaseModel):
  273. """Request to test a REST smart plug connection."""
  274. url: str = Field(..., min_length=1)
  275. method: str = Field(default="GET")
  276. headers: str | None = None # JSON string of custom headers
  277. # The saved plug being edited: its stored headers fill in the placeholder.
  278. plug_id: int | None = None
  279. class RESTTestConnectionResponse(BaseModel):
  280. """Response from REST connection test."""
  281. success: bool
  282. error: str | None = None