问题描述
我正在家庭助理中创建我的第一个集成。
我首先创建了几个单独调用设备 API 的实体。这有效,但正在向 API 发送垃圾邮件。所以我切换到异步函数并且确实有很多超时。现在我将代码更改为使用协调器,以便集成需要调用 API 一次以填充实体状态。协调器中的数据更新正在工作,但实体方法 async_update() 不会被调用,因此我的实体处于未知状态。
我的代码有什么问题,所以我的实体可以更新状态?
async def getFieldValue(coordinator,field):
for data in coordinator.data:
if data['Name'] == field:
_LOGGER.info(data['Value'])
return data['Value']
async def async_setup_platform(hass,config,async_add_entities,discovery_info=None):
host = config[CONF_HOST]
async def async_update_data():
_LOGGER.info("update data")
async with aiohttp.ClientSession() as session:
async with session.get(DATA_URL.replace("[host]",host)) as response:
if response.status == 200:
return await response.json()
else:
raise UpdateFailed(f"Error communicating with API: {response.status}")
coordinator = DataUpdateCoordinator(
hass,_LOGGER,# Name of the data. For logging purposes.
name="sensor",update_method=async_update_data,# Polling interval. Will only be polled if there are subscribers.
update_interval=timedelta(seconds=30),)
await coordinator.async_config_entry_first_refresh()
async_add_entities([
SensorValue(coordinator,"Air quality",AIR_QUALITY_FIELD,"","quality"),SensorValue(coordinator,"CO2 value",CO2_FIELD,"carbon_dioxide","ppm","numeric"),])
class SensorValue(CoordinatorEntity):
def __init__(self,coordinator,name,field,deviceClass,unitOfMeasurement,dataType):
super().__init__(coordinator)
self._state = None
self.sensorName = name
self.field = field
self.deviceClass = deviceClass
self.unitOfMeasurement = unitOfMeasurement
self.datatYPE = dataType
@property
def name(self):
return self.sensorName
@property
def device_class(self):
return self.deviceClass
@property
def unit_of_measurement(self):
return self.unitOfMeasurement
@property
def state(self):
return self._state
async def async_update(self):
_LOGGER.info("update sensor state")
if dataType == "numeric":
self._state = round(float(await getFieldValue(self.coordinator,field)))
elif dataType == "string":
self._state = await getFieldValue(self.coordinator,field)
elif dataType == "boolean":
self._state = bool(int(await getFieldValue(self.coordinator,field)))
elif dataType == "quality":
value = round(float(await getFieldValue(self.coordinator,field)))
if value < 950:
self._state = QUALITY_GOOD
elif value < 1500:
self._state = QUALITY_POOR
else:
self._state = QUALITY_BAD
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)