title: 通过home-assistant监控数值变化 author: zaqai date: 2024-06-27 16:15:20 tags:
通过home-assistant监控数值变化
home-assistant的历史监控还是比较好用的,可以直观地看到数值的变化。学校宿舍有个查看剩余电费的api,把它接入home-assistant,我就可以知道一段时间内用了多少电,或者在电费快没有的时候对我发出提醒。由于没有仔细看home-assistant文档(懒),完全靠一个搜索引擎+AI来尝试,终于找到一个行之有效的方案。只需要定制执行一个python脚本就可以了,不需要nodered(nodered也可以实现,调用service修改数值就可以了,但是没必要)
hass添加辅助元素
在辅助元素里添加一个数值类型,就可以在实体中看到了
python脚本
首先通过api获取电费,再通过hass的api调用service更新数值
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
}
response = requests.get('https://ssn.xjtu.edu.cn/cems/mobile/meterAccount/electricity?roomId=16370',headers=headers)
remaining_balance=0
if response.status_code == 200:
data = response.json()
remaining_balance = data["data"]
print(remaining_balance)
# hass.states.set("sensor.electricity_balance", remaining_balance)
else:
print("Failed to update electricity balance")
url = "http://hassip:8123/api/services/input_number/set_value"
headers = {
"Authorization": "Bearer YOUR_TOKEN",
"content-type": "application/json",
}
data = {"entity_id": "input_number.chuang_xin_gang_su_she_dian_fei","value": remaining_balance}
response = requests.post(url, headers=headers, json=data)
print(response.text)
回复