diff --git a/custom_components/ha_text_ai/sensor.py b/custom_components/ha_text_ai/sensor.py index f93efb8..7f90f0f 100644 --- a/custom_components/ha_text_ai/sensor.py +++ b/custom_components/ha_text_ai/sensor.py @@ -1,64 +1,3 @@ -"""Sensor platform for HA text AI.""" -from datetime import datetime -import logging -from typing import Any, Dict, Optional - -from homeassistant.components.sensor import ( - SensorEntity, - SensorStateClass, - SensorDeviceClass, -) -from homeassistant.config_entries import ConfigEntry -from homeassistant.core import HomeAssistant -from homeassistant.helpers.entity_platform import AddEntitiesCallback -from homeassistant.helpers.typing import StateType -from homeassistant.helpers.update_coordinator import CoordinatorEntity -from homeassistant.util import dt as dt_util - -from .const import ( - DOMAIN, - CONF_API_PROVIDER, - ATTR_QUESTION, - ATTR_RESPONSE, - ATTR_LAST_UPDATED, - ATTR_MODEL, - ATTR_TEMPERATURE, - ATTR_MAX_TOKENS, - ATTR_TOTAL_RESPONSES, - ATTR_SYSTEM_PROMPT, - ATTR_QUEUE_SIZE, - ATTR_API_STATUS, - ATTR_ERROR_COUNT, - ATTR_LAST_ERROR, - ATTR_RESPONSE_TIME, - ATTR_API_VERSION, - ATTR_ENDPOINT_STATUS, - ATTR_REQUEST_COUNT, - ATTR_TOKENS_USED, - ENTITY_ICON, - ENTITY_ICON_ERROR, - ENTITY_ICON_PROCESSING, - STATE_READY, - STATE_PROCESSING, - STATE_ERROR, - STATE_DISCONNECTED, - STATE_RATE_LIMITED, - STATE_INITIALIZING, - STATE_MAINTENANCE, -) -from .coordinator import HATextAICoordinator - -_LOGGER = logging.getLogger(__name__) - -async def async_setup_entry( - hass: HomeAssistant, - entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, -) -> None: - """Set up the HA text AI sensor.""" - coordinator = hass.data[DOMAIN][entry.entry_id] - async_add_entities([HATextAISensor(coordinator, entry)], True) - class HATextAISensor(CoordinatorEntity, SensorEntity): """HA text AI Sensor.""" @@ -73,9 +12,17 @@ class HATextAISensor(CoordinatorEntity, SensorEntity): """Initialize the sensor.""" super().__init__(coordinator) self._config_entry = config_entry + + # Убираем _response из unique_id self._attr_unique_id = config_entry.entry_id - # Добавьте инициализацию состояния + + # Явно задаем имя + self._attr_name = "HA Text AI" + + # Инициализация состояний self._current_state = STATE_INITIALIZING + self._error_count = 0 + self._last_error = None # Девайс инфо self._attr_device_info = { @@ -86,6 +33,11 @@ class HATextAISensor(CoordinatorEntity, SensorEntity): "sw_version": coordinator.api_version, } + @property + def name(self) -> str: + """Return the name of the sensor.""" + return "HA Text AI" + @property def icon(self) -> str: """Return the icon based on the current state.""" @@ -103,6 +55,26 @@ class HATextAISensor(CoordinatorEntity, SensorEntity): return dt_util.as_local(last_response['timestamp']) return self._current_state + @property + def extra_state_attributes(self) -> Dict[str, Any]: + """Return entity specific state attributes.""" + attributes = { + ATTR_TOTAL_RESPONSES: 0, + ATTR_MODEL: self.coordinator.model, + ATTR_API_STATUS: self._current_state, + ATTR_ERROR_COUNT: self._error_count, + ATTR_LAST_ERROR: self._last_error, + } + + last_response = self.coordinator.last_response + if last_response: + attributes.update({ + ATTR_RESPONSE: last_response.get("response", ""), + ATTR_QUESTION: last_response.get("question", ""), + }) + + return attributes + def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" try: @@ -137,34 +109,6 @@ class HATextAISensor(CoordinatorEntity, SensorEntity): self._handle_coordinator_update() self._current_state = STATE_READY - def _handle_coordinator_update(self) -> None: - """Handle updated data from the coordinator.""" - try: - last_response = self.coordinator.last_response - - if last_response: - if last_response.get("error"): - self._state = STATE_ERROR - self._error_count += 1 - elif self.coordinator._is_processing: - self._state = STATE_PROCESSING - elif self.coordinator._is_rate_limited: - self._state = STATE_RATE_LIMITED - elif self.coordinator._is_maintenance: - self._state = STATE_MAINTENANCE - else: - self._state = STATE_READY - else: - self._state = STATE_DISCONNECTED - - except Exception as err: - _LOGGER.error("Error handling update: %s", err, exc_info=True) - self._error_count += 1 - self._last_error = str(err) - self._state = STATE_ERROR - - self.async_write_ha_state() - async def async_reset_error_count(self) -> None: """Reset the error counter.""" self._error_count = 0