mirror of
https://github.com/gangoke/kobrax-lan-hass-component.git
synced 2026-06-09 20:52:13 +02:00
filament entities
This commit is contained in:
@@ -115,11 +115,74 @@ class KobraXSensor(KobraXEntity, SensorEntity):
|
||||
return value
|
||||
|
||||
|
||||
class KobraXFilamentSlotSensor(KobraXEntity, SensorEntity):
|
||||
def __init__(self, coordinator, entry, slot_index: int, field: str) -> None:
|
||||
name_suffix = {
|
||||
"color": f"Filament Slot {slot_index + 1} Color",
|
||||
"type": f"Filament Slot {slot_index + 1} Type",
|
||||
}[field]
|
||||
super().__init__(coordinator, entry, f"filament_slot_{slot_index + 1}_{field}", name_suffix)
|
||||
self._slot_index = slot_index
|
||||
self._field = field
|
||||
|
||||
if field == "color":
|
||||
self._attr_icon = "mdi:palette"
|
||||
elif field == "type":
|
||||
self._attr_icon = "mdi:label"
|
||||
else:
|
||||
self._attr_icon = "mdi:numeric"
|
||||
|
||||
def _slot(self) -> dict[str, Any]:
|
||||
slots = self.state_data.get("ams_slots") or []
|
||||
if not isinstance(slots, list) or self._slot_index >= len(slots):
|
||||
return {}
|
||||
slot = slots[self._slot_index]
|
||||
return slot if isinstance(slot, dict) else {}
|
||||
|
||||
@staticmethod
|
||||
def _to_color_hex(color: Any) -> str | None:
|
||||
if isinstance(color, list) and len(color) >= 3:
|
||||
try:
|
||||
return "#{:02X}{:02X}{:02X}".format(int(color[0]), int(color[1]), int(color[2]))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if isinstance(color, str):
|
||||
cleaned = color.strip().lstrip("#")
|
||||
if len(cleaned) >= 6:
|
||||
return f"#{cleaned[:6].upper()}"
|
||||
return None
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
return bool(self._slot()) and super().available
|
||||
|
||||
@property
|
||||
def native_value(self) -> Any:
|
||||
slot = self._slot()
|
||||
if not slot:
|
||||
return None
|
||||
if self._field == "color":
|
||||
return self._to_color_hex(slot.get("color"))
|
||||
if self._field == "type":
|
||||
material = slot.get("type")
|
||||
return str(material).upper() if material else None
|
||||
return None
|
||||
|
||||
|
||||
async def async_setup_entry(hass, entry, async_add_entities):
|
||||
coordinator = hass.data[DOMAIN][entry.entry_id]["coordinator"]
|
||||
slots = coordinator.data.get("ams_slots") if coordinator.data else []
|
||||
slot_count = len(slots) if isinstance(slots, list) and len(slots) > 0 else 4
|
||||
|
||||
filament_entities: list[SensorEntity] = []
|
||||
for slot_index in range(slot_count):
|
||||
for field in ("color", "type"):
|
||||
filament_entities.append(KobraXFilamentSlotSensor(coordinator, entry, slot_index, field))
|
||||
|
||||
async_add_entities(
|
||||
[
|
||||
KobraXSensor(coordinator, entry, description)
|
||||
for description in SENSORS
|
||||
]
|
||||
+ filament_entities
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user