location_ha_sensor.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """Schemas for Home Assistant entities bound to a storage location (#2824)."""
  2. from datetime import datetime
  3. from typing import Literal
  4. from pydantic import BaseModel, Field, model_validator
  5. from backend.app.schemas.printer_ha_sensor import HADisplayEntity # noqa: F401
  6. class LocationHASensorBase(BaseModel):
  7. location_id: int
  8. name: str = Field(..., min_length=1, max_length=100)
  9. # max_length matches the column (String(255)). The pattern's [a-z0-9_]+ is
  10. # unbounded, so a direct API caller — the picker only ever offers real
  11. # Home Assistant ids — could send a longer one: SQLite stores it, but
  12. # PostgreSQL raises DataError, and the create/update routes only map
  13. # IntegrityError, so it would surface as a 500 instead of a 422.
  14. entity_id: str = Field(..., max_length=255, pattern=r"^(binary_sensor|sensor)\.[a-z0-9_]+$")
  15. kind: Literal["binary", "numeric"] = "binary"
  16. device_class: str | None = Field(default=None, max_length=32)
  17. unit: str | None = Field(default=None, max_length=16)
  18. alert_state: Literal["on", "off"] | None = None
  19. # allow_inf_nan=False: pydantic's lax mode coerces the strings "nan"/"inf"
  20. # into real NaN/Infinity floats. A NaN threshold satisfies the "notify
  21. # needs an alert condition" rule below yet every comparison against it is
  22. # False — a notification that can never fire — and it skips the
  23. # below-vs-above ordering check the same way. Responses serialize NaN as
  24. # null, so the UI would show an empty field over a poisoned row.
  25. alert_above: float | None = Field(default=None, allow_inf_nan=False)
  26. alert_below: float | None = Field(default=None, allow_inf_nan=False)
  27. notify_on_alert: bool = False
  28. show_on_card: bool = True
  29. sort_order: int = Field(default=0, ge=0, le=999)
  30. @model_validator(mode="after")
  31. def validate_kind_matches_entity(self) -> "LocationHASensorBase":
  32. domain = self.entity_id.split(".")[0]
  33. expected = "binary" if domain == "binary_sensor" else "numeric"
  34. if self.kind != expected:
  35. raise ValueError(f"kind must be '{expected}' for a {domain} entity")
  36. # Alert fields are per-kind: a threshold on a battery sensor and an
  37. # on/off alert on a temperature reading are both configuration the
  38. # poller would silently ignore, so reject them at the edge instead.
  39. if self.kind == "binary" and (self.alert_above is not None or self.alert_below is not None):
  40. raise ValueError("alert_above/alert_below only apply to numeric sensors")
  41. if self.kind == "numeric" and self.alert_state is not None:
  42. raise ValueError("alert_state only applies to binary sensors")
  43. if self.alert_above is not None and self.alert_below is not None and self.alert_below >= self.alert_above:
  44. raise ValueError("alert_below must be lower than alert_above")
  45. # A notification with nothing to trigger on would never fire — that
  46. # reads as a broken feature, not as a no-op.
  47. if self.notify_on_alert and not self._has_alert_condition():
  48. raise ValueError("notify_on_alert requires an alert condition")
  49. return self
  50. def _has_alert_condition(self) -> bool:
  51. return self.alert_state is not None or self.alert_above is not None or self.alert_below is not None
  52. class LocationHASensorCreate(LocationHASensorBase):
  53. pass
  54. class LocationHASensorUpdate(BaseModel):
  55. """Partial update. Validated against the merged row in the route, because
  56. the per-kind rules above need fields this payload may not carry."""
  57. name: str | None = Field(default=None, min_length=1, max_length=100)
  58. # Same column-width bound as the base schema; PATCH reaches the same row.
  59. entity_id: str | None = Field(default=None, max_length=255, pattern=r"^(binary_sensor|sensor)\.[a-z0-9_]+$")
  60. kind: Literal["binary", "numeric"] | None = None
  61. device_class: str | None = Field(default=None, max_length=32)
  62. unit: str | None = Field(default=None, max_length=16)
  63. alert_state: Literal["on", "off"] | None = None
  64. # Same allow_inf_nan story as the base schema. The route's merged-row
  65. # re-validation would catch these too, but rejecting them here keeps the
  66. # error attached to the offending field.
  67. alert_above: float | None = Field(default=None, allow_inf_nan=False)
  68. alert_below: float | None = Field(default=None, allow_inf_nan=False)
  69. notify_on_alert: bool | None = None
  70. show_on_card: bool | None = None
  71. sort_order: int | None = Field(default=None, ge=0, le=999)
  72. class LocationHASensorResponse(LocationHASensorBase):
  73. # Reads must tolerate what writes now reject, or one legacy row 500s the
  74. # whole list. Three constraints are relaxed here on purpose:
  75. #
  76. # * the NaN/inf thresholds a row could carry before allow_inf_nan landed —
  77. # serialization turns them into null, which is also what the edit form
  78. # should show;
  79. # * the entity_id length bound, for a row created before max_length existed
  80. # (SQLite never enforced the column's 255, so those rows are real);
  81. # * the entity_id pattern, which the same generation of rows predates.
  82. #
  83. # Every one of them is still rejected on the way in, so this widens what
  84. # can be read back, never what can be stored.
  85. alert_above: float | None = None
  86. alert_below: float | None = None
  87. entity_id: str
  88. id: int
  89. last_state: str | None = None
  90. last_changed: datetime | None = None
  91. last_checked: datetime | None = None
  92. created_at: datetime
  93. updated_at: datetime
  94. class Config:
  95. from_attributes = True
  96. class LocationHASensorReading(BaseModel):
  97. """One sensor's live state, as the filament card and inventory table render it."""
  98. id: int
  99. name: str
  100. entity_id: str
  101. kind: str
  102. device_class: str | None = None
  103. unit: str | None = None
  104. # Raw HA state: "on"/"off" for binary, the numeric string for sensors.
  105. # None when the entity is unavailable or has not been polled yet.
  106. state: str | None = None
  107. value: float | None = None # numeric sensors only, parsed from state
  108. alerting: bool = False
  109. reachable: bool = True
  110. alert_state: str | None = None
  111. alert_above: float | None = None
  112. alert_below: float | None = None
  113. last_changed: datetime | None = None
  114. # Lets a consumer that fetched the unfiltered (show_on_card=False) list
  115. # still pick out the card-visible subset itself, instead of issuing a
  116. # second request for the same location.
  117. show_on_card: bool = True