Modification of ADS component

I’m trying to modify the ADS component to suit my needs.
2 things I’m trying to accomplish:

  • Create an update interval parameter, so the entity only gets updated every X seconds
  • Do decimal rounding before writing the value to HA

Here is my modified code, a snippet of init.py ADS hub:

        def update(name, value):
            """Handle device notifications."""
            _LOGGER.debug("Variable %s changed its value to %d", name, value)

            # Modification
            needsupdate = False

            if self._state_dict[state_key] == None:
                needsupdate = True
            else:
                states = self.hass.states.get('sensor.' + self._name)
                update_after = dt_util.utcnow() - timedelta(seconds=update_interval)
                if update_after > states.last_updated:
                    needsupdate = True

            if needsupdate == True:
                if factor is None:
                    tempvalue = value
                else:
                    tempvalue = value / factor

                if round_perform:
                    x = Decimal(tempvalue)
                    if round_decimal == 0:
                        value = round(x, None)
                    else:
                        value = round(x, round_decimal)
                else:
                    value = tempvalue

                self._state_dict[state_key] = value
                asyncio.run_coroutine_threadsafe(async_event_set(), self.hass.loop)
                self.schedule_update_ha_state()

2 problems I encounter:

  • When HA restarts, the log spits out the following error:
2020-05-31 01:35:14 ERROR (Dummy-9) [root] Uncaught exception
Traceback (most recent call last):
  File "_ctypes/callbacks.c", line 232, in 'calling callback function'
  File "/usr/local/lib/python3.7/site-packages/pyads/pyads_ex.py", line 678, in wrapper
    return callback(notification, data_name)
  File "/config/custom_components/ads_custom/__init__.py", line 269, in _device_notification_callback
    notification_item.callback(notification_item.name, value)
  File "/config/custom_components/ads_custom/__init__.py", line 302, in update
    if update_after > states.last_updated:
AttributeError: 'NoneType' object has no attribute 'last_updated'

This is reasonable since the entity is freshly registered and there is no last_updated value yet.

  • I needed to hard-code it to sensors: “states = self.hass.states.get(‘sensor.’ + self._name)” for this to work, but I want to extend it also to the other entities like binary_sensor.
    Can I make this versatile in some way?