本帖最后由 kmyq 于 2024-9-25 10:01 编辑
一直当白嫖别人经验的小白,今天也来分享一下自己的经验
之前一直用大佬的节假日库,可以获得每天法定假节日,然后每天拉窗帘起床很完美。
突然有一天用不了了,发现被墙,于是想用代理获得,却搞不明白jinjia2怎么通过代理get json。
于是萌生用Python获得json -> 配置一个集成 ->配置自动化的思路。
代码找GPT写个大概自己改改很快就用起来了,一直都在白嫖,自己成功搞了个东西,还是很开心的。
---------
环境:docker HA;
Python3应该自带的吧
1. 首先在/config/python_scripts/ 添加一个py文件 import_json.py
如果你想加一些自定义的的节日或者逻辑,可以自己在最后get_workday_status判断dt为某一天让status为True注意:有时候会遇到因为注释报编码错误,类似:SyntaxError: Non-UTF-8 code starting with '\xb2'
去掉# 后面的所有中文内容应该就可以解决
<font face="微软雅黑">
import requests
from datetime import datetime, timedelta
import json
import os
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
PROXY = "http://192.168.1.1:8080" # 改成你的代理地址
JSON_URL = "https://cdn.jsdelivr.net/gh/NateScarlet/holiday-cn@master/{}.json"
LOCAL_FILE_PATH = "/config/python_scripts/holiday_data.json" # json保存的位置,如果前面你的py位置不一样,最好改一下
UPDATE_INTERVAL_DAYS = 2
def download_json():
year = datetime.now().year
url = JSON_URL.format(year)
proxies = {"http": PROXY, "https": PROXY}
try:
response = requests.get(url, timeout=10, proxies=proxies) # 不需要代理就去掉, proxies=proxies
response.raise_for_status()
return response.json()
except requests.RequestException as e:
logging.error(f"Error downloading JSON: {e}")
return None
def save_json(data):
try:
with open(LOCAL_FILE_PATH, 'w') as f:
json.dump(data, f)
logging.info("JSON data saved successfully")
except IOError as e:
logging.error(f"Error saving JSON data: {e}")
def load_json():
try:
if os.path.exists(LOCAL_FILE_PATH):
with open(LOCAL_FILE_PATH, 'r') as f:
data = json.load(f)
return data
else:
logging.warning("Local JSON file not found")
return None
except IOError as e:
logging.error(f"Error loading JSON data: {e}")
return None
def should_update():
# return True
if not os.path.exists(LOCAL_FILE_PATH):
return True
file_modified_time = datetime.fromtimestamp(
os.path.getmtime(LOCAL_FILE_PATH))
return datetime.now() - file_modified_time > timedelta(days=UPDATE_INTERVAL_DAYS)
def get_workday_status(dt):
status = False
saves = False
if should_update():
logging.info("Updating holiday data")
data = download_json()
if data:
save_json(data)
saves = True
else:
data = load_json()
if not data:
logging.error("No holiday data available")
return json.dumps({"status": status, "date": dt, "isOffDay": "No holiday data available", "saves": saves})
# data = load_json()
# today = datetime.now().strftime('%Y-%m-%d')
is_weekend = datetime.strptime(dt,'%Y-%m-%d').weekday() in [5, 6]
status = (False if is_weekend else True)
# print(status)
isOffDay = False
for day in data.get('days', []):
if day.get('date') == dt:
status = False if day.get('isOffDay') else True
isOffDay = day.get('isOffDay')
break
# return json.dumps({"status": status, "date": today, "isOffDay": day.get('isOffDay')})
# 如果你想加一些自定义的的节日或者逻辑,可以自己在最后get_workday_status判断dt为某一天让status为True
# if dt in ['2024-09-11']:
# status = True
# isOffDay = dt
return json.dumps({"status": status, "date": dt, "isOffDay": isOffDay, "saves": saves})
if __name__ == "__main__":
print(get_workday_status(datetime.now().strftime('%Y-%m-%d')))
</font>
2.在中configuration.yaml添加集成
<font face="微软雅黑">
command_line:
- sensor:
name: holiday_json_data
command: "python3 /config/python_scripts/import_json.py"
value_template: '{{ value_json }}'
scan_interval: 7200
json_attributes:
- status
</font>
3.重启HA,然后在开发着工具里搜holiday应该就能看到一个状态了
4.我的拉窗帘配置,在自动化里用yaml格式添加如下,我的窗帘不太好,防止一次失败导致迟到,我循环了5次。-- 记得改成你自己窗帘集成
<font face="微软雅黑">
alias: 每天早上逐渐打开窗帘至40%
description: 多次尝试打开窗帘,直到窗帘打开到40%或最多尝试5次
trigger:
- platform: time
at: "08:10:00"
condition:
- condition: state
entity_id: sensor.holiday_json_data
state: true
attribute: status
action:
- repeat:
count: 5
sequence:
- condition: template
value_template: >-
{{ state_attr('cover.babai_190812_9eea_curtain', 'current_position')
| int < 30 }}
- target:
entity_id: cover.babai_190812_9eea_curtain
data:
position: 40
action: cover.set_cover_position
- delay:
hours: 0
minutes: 0
seconds: 10
milliseconds: 0
mode: single
</font>
------第一次分享,有什么问题见谅(卑微
|