HA插件更新机制

方式1

以和风天气为实例

计时方式: TIME_BETWEEN_UPDATES = timedelta(seconds=1800)

首先导入 from homeassistant.util import Throttle

WeatherData类中的update函数中加入装饰器 @Throttle(TIME_BETWEEN_UPDATES)

1
2
3
4
class WeatherData(object):
@Throttle(TIME_BETWEEN_UPDATES)
def update(self):
pass

HeWeatherSensor 类中的update函数中调用Data类中的更新函数

1
2
3
4
class HeWeatherSensor(Entity):
def update(self):
self._data.update()
self._updatetime = self._data.updatetime

平台设置内传入参数,下同

1
2
3
4
5
6
7
8
9
10
11
def setup_platform(hass, config, add_devices, discovery_info=None):
_LOGGER.info("Setup platform sensor.HeWeather")
city = config.get(CONF_CITY)
appkey = config.get(CONF_APPKEY)
aqi_city = config.get(CONF_AQI_CITY)
data = WeatherData(hass, city, appkey, aqi_city)

dev = []
for option in config[CONF_OPTIONS]:
dev.append(HeWeatherSensor(data, option))
add_devices(dev, True)

方式2

在Data类中 调用Throttle函数

1
2
3
4
5
6
7
8
9
10
11
class Data(object):
"""Get the latest data from Darksky."""

def __init__(self, **args):

self.update = Throttle(interval)(self._update)


def _update(self):
# 更新操作
pass

然后在实体类中调用数据类的更新

1
2
3
4
5
6
7
8
class Sensor(Entity):
"""Implementation of a Dark Sky sensor."""

def __init__(self, forecast_data, **args):
self.forecast_data = forecast_data

def update(self):
self.forecast_data.update()
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2017-2021 More Star

请我喝杯咖啡吧~

支付宝
微信