Skip to content

Instantly share code, notes, and snippets.

@liantian-cn
Last active June 21, 2024 15:33
Show Gist options
  • Save liantian-cn/7e7c40db8843c92fdff616540e7f5b0e to your computer and use it in GitHub Desktop.
Save liantian-cn/7e7c40db8843c92fdff616540e7f5b0e to your computer and use it in GitHub Desktop.
根据日出日落时间调节易来的色温和亮度
{
"latitude": 39.9042,
"longitude": 116.4074,
"timezone": "Asia/Shanghai",
"min_temperature": 2700,
"max_temperature": 5500,
"min_brightness": 1,
"max_brightness": 80,
"devices": [
]
}
FROM alpine:latest
ENV TZ=Asia/Shanghai
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
RUN echo "@testing https://mirrors.tuna.tsinghua.edu.cn/alpine/edge/testing" >> /etc/apk/repositories
RUN apk update
RUN apk add bash python3 py3-pip py3-astral@testing py3-tz@testing py3-netifaces@testing
RUN ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
RUN pip install python-miio --break-system-packages
# Run a cron job
COPY crontab.txt /crontab.txt
RUN /usr/bin/crontab /crontab.txt
RUN mkdir /app
COPY main.py /app/main.py
COPY config.json /app/config.json
RUN chmod +x /app/main.py
CMD ["/usr/sbin/crond", "-f", "-l", "2"]
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import pytz
from miio import CloudInterface
from miio import Yeelight
from miio.exceptions import DeviceException
from astral import LocationInfo
from astral.sun import sun
from datetime import datetime, timedelta
config = json.load(open("config.json"))
__doc__ = """
pip install python-miio
pip install astral
pip install pytz
"""
def calculate_sunrise_sunset():
# 定位信息
location = LocationInfo(latitude=config["latitude"], longitude=config["longitude"], timezone=config["timezone"])
# 获取今天的日期
today = datetime.today()
# 计算日出和日落时间
s = sun(location.observer, date=today, tzinfo=location.timezone)
print(s)
# 返回日出和日落时间
return s['sunrise'], s['noon'], s['sunset']
def get_light_properties():
utc_now = datetime.now(pytz.UTC)
now = utc_now.astimezone(pytz.timezone(config["timezone"]))
sunrise, noon, sunset = calculate_sunrise_sunset()
before_sunrise = now < sunrise - timedelta(hours=1)
after_sunset = now > sunset + timedelta(hours=1)
is_noon = now == noon
brightness = config["min_brightness"]
temperature = config["min_temperature"]
# 根据时间关系设置色温和亮度
if before_sunrise or after_sunset:
# 日出前1小时和日落后1小时,设置最低亮度和色温
brightness = config["min_brightness"]
temperature = config["min_temperature"]
elif is_noon:
# 正午时间,设置最大亮度和最低色温
brightness = config["max_brightness"]
temperature = config["max_temperature"]
elif now < noon:
# 计算上午的时间比例
time_since_sunrise = (now - sunrise).total_seconds()
time_until_noon = (noon - sunrise).total_seconds()
# 计算亮度
brightness = config["min_brightness"] + (config["max_brightness"] - config["min_brightness"]) * (time_since_sunrise / time_until_noon)
# 计算色温
temperature = config["min_temperature"] + (config["max_temperature"] - config["min_temperature"]) * (time_since_sunrise / time_until_noon)
elif now > noon:
# 计算下午的时间比例
time_since_noon = (now - noon).total_seconds()
time_until_sunset = (sunset - noon).total_seconds()
# 计算亮度
brightness = config["max_brightness"] - (config["max_brightness"] - config["min_brightness"]) * (time_since_noon / time_until_sunset)
# 计算色温
temperature = config["max_temperature"] + (config["max_temperature"] - config["min_temperature"]) * (time_since_noon / time_until_sunset)
return brightness, temperature
def main():
if len(config["devices"]) == 0:
devices = []
print("当前没有设备,请输入设备登录信息,录入设备\n")
username = input("请输入米家账号:")
password = input("请输入米家密码:")
ci = CloudInterface(username=username, password=password)
devs = ci.get_devices()
for did, dev in devs.items():
print(dev)
if dev.model.startswith("yeelink"):
devices.append({
"model": dev.model,
"token": dev.token,
"ip": dev.ip,
"name": dev.name
})
config["devices"] = devices
json.dump(config, open("config.json", "w", encoding="utf-8"), indent=4)
else:
brightness, temperature = get_light_properties()
for dev in config["devices"]:
if dev["model"].startswith("yeelink"):
try:
dev = Yeelight(dev["ip"], dev["token"])
dev.set_brightness(brightness)
dev.set_color_temp(temperature)
except DeviceException as e:
print(f'更新{dev["ip"]}故障')
print(e)
# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment