gillesvs / librelink

Librelink integration for Home Assistant
MIT License
21 stars 6 forks source link

Issue identified : IndexError: list index out of range in LibreLink Sensor #19

Open hdmvide opened 3 months ago

hdmvide commented 3 months ago

Hello,

I encountered an IndexError: list index out of range when using the LibreLink custom component in Home Assistant. Below is the error traceback from the logs:

2024-05-22 21:54:02.801 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 258, in _handle_refresh_interval
    await self._async_refresh(log_failures=True, scheduled=True)
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 414, in _async_refresh
    self.async_update_listeners()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 168, in async_update_listeners
    update_callback()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 492, in _handle_coordinator_update
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1009, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1132, in _async_write_ha_state
    state, attr, capabilities, shadowed_attr = self.__async_calculate_state()
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1067, in __async_calculate_state
    state = self._stringify_state(available)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1015, in _stringify_state
    if (state := self.state) is None:
                 ^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 542, in state
    unit_of_measurement = self.unit_of_measurement
                          ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/librelink/sensor.py", line 201, in unit_of_measurement
    if self.coordinator.data[self.index]:
       ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
IndexError: list index out of range
2024-05-22 22:02:02.810 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 258, in _handle_refresh_interval
    await self._async_refresh(log_failures=True, scheduled=True)
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 414, in _async_refresh
    self.async_update_listeners()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 168, in async_update_listeners
    update_callback()
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 492, in _handle_coordinator_update
    self.async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1009, in async_write_ha_state
    self._async_write_ha_state()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1132, in _async_write_ha_state
    state, attr, capabilities, shadowed_attr = self.__async_calculate_state()
                                               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1067, in __async_calculate_state
    state = self._stringify_state(available)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1015, in _stringify_state
    if (state := self.state) is None:
                 ^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/sensor/__init__.py", line 542, in state
    unit_of_measurement = self.unit_of_measurement
                          ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/librelink/sensor.py", line 201, in unit_of_measurement
    if self.coordinator.data[self.index]:
       ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
IndexError: list index out of range

Steps to Reproduce:

Install the LibreLink custom component. Configure it with the required settings. Start Home Assistant. Observe the logs for the IndexError.

Possible Cause:

The error seems to be due to accessing an index in self.coordinator.data that does not exist. This can happen if self.index is out of range.

Proposed Fix:

Adding a check to ensure that self.index is within the bounds of self.coordinator.data before accessing it can resolve this issue. Here is an example modification:

@property
def native_value(self):
    """Return the native value of the sensor."""
    result = None

    if (
        self.coordinator.data is not None
        and len(self.coordinator.data) > self.index
        and self.coordinator.data[self.index] is not None
    ):
        if self.key == "value":
            if self.uom == MG_DL:
                result = int(
                    self.coordinator.data[self.index]["glucoseMeasurement"]["ValueInMgPerDl"]
                )
            elif self.uom == MMOL_L:
                result = round(
                    float(
                        self.coordinator.data[self.index]["glucoseMeasurement"]["ValueInMgPerDl"]
                    )
                    / MMOL_DL_TO_MG_DL,
                    1,
                )
        elif self.key == "trend":
            if "TrendArrow" in self.coordinator.data[self.index]["glucoseMeasurement"]:
                result = GLUCOSE_TREND_MESSAGE[
                    (
                        self.coordinator.data[self.index]["glucoseMeasurement"]["TrendArrow"]
                    )
                    - 1
                ]
        elif self.key == "sensor":
            if "sensor" in self.coordinator.data[self.index] and self.coordinator.data[self.index]["sensor"] is not None:
                result = int(
                    (
                        time.time()
                        - (self.coordinator.data[self.index]["sensor"]["a"])
                    )
                    / 86400
                )
        elif self.key == "delay":
            if "Timestamp" in self.coordinator.data[self.index]["glucoseMeasurement"]:
                result = int(
                    (
                        datetime.now()
                        - datetime.strptime(
                            self.coordinator.data[self.index]["glucoseMeasurement"]["Timestamp"],
                            "%m/%d/%Y %I:%M:%S %p",
                        )
                    ).total_seconds()
                    / 60
                )

    return result

Environment:

Home Assistant version Code: 2024.5.3 LibreLink custom component version: 1.2.3 Operating System: RaspberryOS Debian GNU/Linux 12 (bookworm)
Kernel: Linux 6.6.28+rpt-rpi-v8 Architecture: arm64

Thank you for your attention to this issue. Please let me know if you need any further information.

Best regards,