13 Commits

Author SHA1 Message Date
星光-k
2d9959cd77 Add files via upload 2025-02-08 11:58:02 +00:00
星光-k
10f8b8182b Delete bin/vendor/1 2025-02-08 19:57:27 +08:00
星光-k
469aec331a Add files via upload 2025-02-08 11:56:46 +00:00
星光-k
a8247c1932 Create 1 2025-02-08 19:55:48 +08:00
星光-k
f37acd5a20 Update install.sh 2025-02-08 19:20:25 +08:00
星光-k
6836c448be Update README.md 2025-02-08 19:18:32 +08:00
星光-k
2efc2c4f5d Update install.sh 2025-02-08 15:21:57 +08:00
星光-k
01f62f696b Update install.sh 2025-02-08 15:19:52 +08:00
星光-k
e8b3668ed7 更新 weather.py 2025-02-08 01:17:31 +00:00
星光-k
b840257988 更新 main.py 2025-02-08 01:12:39 +00:00
星光-k
3541ecc135 Update start.sh 2025-01-27 21:52:10 +08:00
星光-k
aa6df92479 更新 clock.py 2025-01-23 15:19:55 +00:00
星光-k
da65b28227 更新 main.py 2025-01-23 15:19:04 +00:00
15 changed files with 235 additions and 151 deletions

View File

@@ -66,6 +66,7 @@ sudo reboot
--zh 设置系统语言为zh_CN,UTF-8 --zh 设置系统语言为zh_CN,UTF-8
--cn 替换apt镜像源为中国镜像源 --cn 替换apt镜像源为中国镜像源
--gitcn 克隆中国仓库 --gitcn 克隆中国仓库
--pip-offline pip依赖离线安装
--pisugar-wifi-conf 安装pisugar-wifi-conf --pisugar-wifi-conf 安装pisugar-wifi-conf
--pisugar-power-manager 安装pisugar-power-manager --pisugar-power-manager 安装pisugar-power-manager
--version <tag> 版本号(使用方法 --version + 仓库标签,格式例如 v1.x.x ,可以是主仓库main) --version <tag> 版本号(使用方法 --version + 仓库标签,格式例如 v1.x.x ,可以是主仓库main)
@@ -73,22 +74,29 @@ sudo reboot
``` ```
### ###
```Bash ```Bash
#中国源默认设置 #中国源默认设置(不加参数)
curl -sSL https://gitee.com/xingguangk/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash curl -sSL https://gitee.com/xingguangk/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash
``` ```
```Bash ```Bash
#中国源参数设置(不使用--debug参数) #中国源参数设置(不使用--debug参数,替换cn镜像源,pip在线安装,不安装pisugar)
curl -sSL https://gitee.com/xingguangk/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash -s -- --zh --cn --gitcn --pisugar-power-manager --pisugar-wifi-conf --version <tag> curl -sSL https://gitee.com/xingguangk/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash -s -- --zh --cn --gitcn --version <tag>
``` ```
```Bash ```Bash
#默认源默认设置 #中国源参数设置(不使用--debug参数,替换cn镜像源,pip依赖离线安装,不安装pisugar)
curl -sSL https://gitee.com/xingguangk/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash -s -- --zh --cn --gitcn --pip-offline --version <tag>
```
```Bash
#默认源默认设置(不加参数)
curl -sSL https://github.com/kxgx/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash curl -sSL https://github.com/kxgx/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash
``` ```
```Bash ```Bash
#默认源全参数设置(不使用--debug参数) #默认源默认设置(不使用--debug参数,替换cn镜像源,pip在线安装,不安装pisugar)
curl -sSL https://github.com/kxgx/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash -s -- --zh --cn --gitcn --pisugar-power-manager --pisugar-wifi-conf --version <tag> curl -sSL https://github.com/kxgx/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash -s -- --zh --cn --gitcn --version <tag>
```
```Bash
#默认源默认设置(不使用--debug参数,替换cn镜像源,pip依赖离线安装,不安装pisugar)
curl -sSL https://github.com/kxgx/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash -s -- --zh --cn --gitcn --pip-offline --version <tag>
``` ```
## 需要安装的软件和依赖: ## 需要安装的软件和依赖:
参考 参考
微雪电子 https://www.waveshare.net/wiki/2.13inch_e-Paper_HAT+#Raspberry_Pi 微雪电子 https://www.waveshare.net/wiki/2.13inch_e-Paper_HAT+#Raspberry_Pi

View File

@@ -202,43 +202,40 @@ def Partial_refresh(): # 局刷函数
power_str1 = power_battery() power_str1 = power_battery()
power_str = power_str1 power_str = power_str1
Local_strong_brush() # 局部强刷 Local_strong_brush() # 局部强刷
try:
##################屏幕初始化#########################
epd = epd2in13_V4.EPD() # 初始化
epd.init() # 设定屏幕刷新模式
# epd.Clear(0xFF) # 清除屏幕内容
##################屏幕初始化#########################
logging.info("Width = %s, Height = %s", format(epd.width), format(epd.height)) # 打印屏幕高度及宽度
logging.info("Initialize and clear the display") # 屏幕开始准备相关展示
info_image = Image.new('1', (epd.height, epd.width), 255) # 画布创建准备
draw = ImageDraw.Draw(info_image)
Basic_refresh() # 全局刷新
Partial_refresh() # 局部刷新
epd.init()
epd.Clear(0xFF)
epd.sleep()
except IOError as e:
logging.info(e)
except KeyboardInterrupt:
logging.info("Keyboard interrupt detected, exiting gracefully.")
epd.init()
epd.Clear(0xFF) # 清除屏幕内容
epd.sleep() # 使屏幕进入休眠状态
epd2in13_V4.epdconfig.module_exit() # 清理资源
exit()
except Exception as e: retry_interval = 180 # 设置重试间隔时间(秒)
logging.error("An unexpected error occurred: %s", e) while True:
epd.init() try:
epd.Clear(0xFF) # 清除屏幕内容 ##################屏幕初始化#########################
epd.sleep() # 使屏幕进入休眠状态 epd = epd2in13_V4.EPD() #初始化
epd2in13_V4.epdconfig.module_exit() # 清理资源 epd.init()#设定屏幕刷新模式
exit() #epd.Clear(0xFF) #清除屏幕内容
##################屏幕初始化#########################
logging.info("Width = %s, Height = %s", format(epd.width), format(epd.height)) #打印屏幕高度及宽度
logging.info("初始化并清空显示屏")#屏幕开始准备相关展示
info_image = Image.new('1', (epd.height, epd.width), 255) #画布创建准备
draw = ImageDraw.Draw(info_image)
Basic_refresh() #全局刷新
Partial_refresh() #局部刷新
epd.init()
epd.Clear(0xFF)
epd.sleep()
time.sleep(300)
break # 如果脚本执行成功,则退出循环
except (OSError, Exception) as e: # 捕获你提到的异常
logging.error("发生了错误: %s", e)
time.sleep(retry_interval) # 等待一段时间后重试
except KeyboardInterrupt:
logging.info("检测到键盘中断,正在清理并退出")
epd.init()
epd.Clear(0xFF) # 清除屏幕内容
epd.sleep() # 使屏幕进入休眠状态
epd2in13_V4.epdconfig.module_exit() # 清理资源
exit()
# 脚本正常结束后的清理操作 # 脚本正常结束后的清理操作
epd.init() epd.init()
epd.Clear(0xFF) # 清除屏幕内容 epd.Clear(0xFF) # 清除屏幕内容
epd.sleep() # 使屏幕进入休眠状态 epd.sleep() # 使屏幕进入休眠状态
epd2in13_V4.epdconfig.module_exit() # 清理资源 epd2in13_V4.epdconfig.module_exit() # 清理资源
exit() exit()

View File

@@ -18,6 +18,8 @@ USE_CN_GIT=false
USE_PISUGAR_WIFI_CONF=false USE_PISUGAR_WIFI_CONF=false
# 检查是否安装pisugar-power-manager # 检查是否安装pisugar-power-manager
USE_PISUGAR_POWER_MANAGER=false USE_PISUGAR_POWER_MANAGER=false
# 检查是否使用离线安装pip依赖
USE_OFFLINE_PIP=false
# 解析命令行参数 # 解析命令行参数
while [ "$#" -gt 0 ]; do while [ "$#" -gt 0 ]; do
@@ -31,6 +33,9 @@ while [ "$#" -gt 0 ]; do
--gitcn) --gitcn)
USE_CN_GIT=true USE_CN_GIT=true
;; ;;
--pip-offline)
USE_OFFLINE_PIP=true
;;
--pisugar-wifi-conf) --pisugar-wifi-conf)
USE_PISUGAR_WIFI_CONF=true USE_PISUGAR_WIFI_CONF=true
;; ;;
@@ -203,23 +208,7 @@ install_packages() {
fi fi
} }
# 安装pip包函数 install_Ink-screen-clock() {
install_pip_packages() {
echo "正在安装pip软件包"
if ! sudo pip3 install -i "$PIPY_MIRROR" spidev borax pillow requests Flask; then
echo "pip软件包安装失败如果是最新版系统或是非lite系统" >&2
echo "请手动运行sudo pip3 install -i "$PIPY_MIRROR" spidev borax pillow requests --break-system-packages" >&2
exit 1
fi
}
# 复制服务文件并设置为开机启动
setup_service() {
local service_path="raspi_e-Paper.service"
local service1_path="e-Paper_clean.service"
local service_file_path="$HOME/2.13-Ink-screen-clock/bin/$service_path"
local service1_file_path="$HOME/2.13-Ink-screen-clock/bin/$service1_path"
# 检查墨水屏时钟仓库是否存在 # 检查墨水屏时钟仓库是否存在
if [ ! -d "$HOME/2.13-Ink-screen-clock" ]; then if [ ! -d "$HOME/2.13-Ink-screen-clock" ]; then
echo "正在克隆仓库" echo "正在克隆仓库"
@@ -234,6 +223,41 @@ setup_service() {
else else
echo "仓库文件夹已存在,跳过克隆" echo "仓库文件夹已存在,跳过克隆"
fi fi
}
# 安装pip包函数
install_oline_pip_packages() {
echo "正在安装pip软件包"
if ! sudo pip3 install -i "$PIPY_MIRROR" -r "$HOME/2.13-Ink-screen-clock/bin/requirements.txt"; then
echo "pip软件包安装失败如果是最新版系统或是非lite系统" >&2
echo "请手动运行sudo pip3 install -i "$PIPY_MIRROR" -r "$HOME/2.13-Ink-screen-clock/bin/requirements.txt" --break-system-packages" >&2
exit 1
fi
}
install_offline_pip_packages() {
echo "正在安装pip软件包"
if ! sudo pip3 install --no-index --find-links="$HOME/2.13-Ink-screen-clock/bin/vendor" -r "$HOME/2.13-Ink-screen-clock/bin/requirements.txt"; then
echo "pip软件包安装失败如果是最新版系统或是非lite系统" >&2
echo "请手动运行sudo pip3 install --no-index --find-links="$HOME/2.13-Ink-screen-clock/bin/vendor" -r "$HOME/2.13-Ink-screen-clock/bin/requirements.txt" --break-system-packages" >&2
exit 1
fi
}
install_pip_packages() {
if [ "$USE_OFFLINE_PIP" = true ]; then
install_offline_pip_packages
else
install_oline_pip_packages
fi
}
# 复制服务文件并设置为开机启动
setup_service() {
local service_path="raspi_e-Paper.service"
local service1_path="e-Paper_clean.service"
local service_file_path="$HOME/2.13-Ink-screen-clock/bin/$service_path"
local service1_file_path="$HOME/2.13-Ink-screen-clock/bin/$service1_path"
# 检查服务文件是否存在 # 检查服务文件是否存在
if [ -f "$service_file_path" ] && [ -f "$service1_file_path" ]; then if [ -f "$service_file_path" ] && [ -f "$service1_file_path" ]; then
@@ -306,6 +330,7 @@ if [ -f /etc/debian_version ]; then
echo "执行Debian 11 (Bullseye) 相关操作" echo "执行Debian 11 (Bullseye) 相关操作"
update_sources_list "bullseye" update_sources_list "bullseye"
install_packages install_packages
install_Ink-screen-clock
install_pip_packages install_pip_packages
setup_service setup_service
#install_webui #install_webui
@@ -316,6 +341,7 @@ if [ -f /etc/debian_version ]; then
echo "执行Debian 12 (Bookworm) 相关操作" echo "执行Debian 12 (Bookworm) 相关操作"
update_sources_list "bookworm" update_sources_list "bookworm"
install_packages install_packages
install_Ink-screen-clock
install_pip_packages install_pip_packages
setup_service setup_service
#install_webui #install_webui

View File

@@ -55,28 +55,28 @@ def set_system_time_from_hwclock(utc=True):
hwclock_args = ['sudo', 'hwclock', '--hctosys'] hwclock_args = ['sudo', 'hwclock', '--hctosys']
if not utc: if not utc:
hwclock_args.append('--localtime') hwclock_args.append('--localtime')
logging.debug(f"Executing hwclock command: {' '.join(hwclock_args)}") logging.debug(f"Executing hwclock command: {' '.join(hwclock_args)}")
# 使用 subprocess.run 执行 hwclock --hctosys 并捕获输出 # 使用 subprocess.run 执行 hwclock --hctosys 并捕获输出
result = subprocess.run(hwclock_args, result = subprocess.run(hwclock_args,
check=True, # 如果命令失败,则抛出 CalledProcessError 异常 check=True, # 如果命令失败,则抛出 CalledProcessError 异常
stdout=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, stderr=subprocess.PIPE,
text=True) text=True)
# 等待一小段时间以确保时间更新完成 # 等待一小段时间以确保时间更新完成
time.sleep(0.1) # 根据需要调整 time.sleep(0.1) # 根据需要调整
# 记录调用 hwclock 后的时间 # 记录调用 hwclock 后的时间
after_time = datetime.datetime.now() after_time = datetime.datetime.now()
logging.debug("System time successfully set from hardware clock.") logging.debug("System time successfully set from hardware clock.")
logging.debug(f"System time after hwclock call: {after_time}") logging.debug(f"System time after hwclock call: {after_time}")
# 检查时间是否发生了倒退 # 检查时间是否发生了倒退
if after_time < before_time: if after_time < before_time:
logging.warning(f"Time went backwards after hwclock call: before={before_time}, after={after_time}") logging.warning(f"Time went backwards after hwclock call: before={before_time}, after={after_time}")
return True return True
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
logging.error(f"Failed to set system time from hardware clock: {e.stderr}") logging.error(f"Failed to set system time from hardware clock: {e.stderr}")
@@ -87,18 +87,17 @@ def set_system_time_from_hwclock(utc=True):
def get_time(): def get_time():
global has_set_system_time global has_set_system_time
if not has_set_system_time: if not has_set_system_time:
# 尝试从硬件时钟设置系统时间,默认假设 RTC 是 UTC # 尝试从硬件时钟设置系统时间,默认假设 RTC 是 UTC
success = set_system_time_from_hwclock(utc=True) success = set_system_time_from_hwclock(utc=True)
# 无论成功与否,都更新标志变量以避免重复尝试 # 无论成功与否,都更新标志变量以避免重复尝试
has_set_system_time = True has_set_system_time = True
# 获取并返回当前时间,格式为 HH:MM 大写 # 获取并返回当前时间,格式为 HH:MM 大写
current_time = time.strftime('%H:%M').upper() current_time = time.strftime('%H:%M').upper()
logging.debug(f"Returning current time: {current_time}") logging.debug(f"Returning current time: {current_time}")
return current_time return current_time
def Get_ipv4_address(): # 获取当前的IP地址 def Get_ipv4_address(): # 获取当前的IP地址
try: try:
ip_output = subprocess.check_output( ip_output = subprocess.check_output(
@@ -108,14 +107,36 @@ def Get_ipv4_address(): # 获取当前的IP地址
return filtered_ips[0] if filtered_ips else "地址获取失败" return filtered_ips[0] if filtered_ips else "地址获取失败"
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
return "获取失败" return "获取失败"
# 全局变量声明
last_power = None # 用于存储上一次获取的电量值
last_power_time = 0 # 用于存储上一次获取电量的时间戳
def power_battery(): # 获取当前电池电量 def power_battery(): # 获取当前电池电量
return str(int(subprocess.check_output( global last_power, last_power_time
u"echo \"get battery\" | nc -q 0 127.0.0.1 8423|awk -F':' '{print int($2)}'", current_time = time.time() # 获取当前时间戳
shell=True).decode('gbk'))) + u'%'
# 每3分钟或首次获取时更新
if (current_time - last_power_time >= 180) or (last_power is None):
try:
# 执行命令获取电池电量
result = subprocess.check_output(
u"echo \"get battery\" | nc -q 0 127.0.0.1 8423 | awk -F':' '{print int($2)}'",
shell=True, stderr=subprocess.STDOUT
).decode('gbk').strip()
new_power = f"{int(result)}%" # 格式化电量值
# 仅在电量变化或首次时更新显示
if new_power != last_power or last_power is None:
logging.info(f"电池电量更新: {new_power}")
last_power = new_power # 更新缓存值
last_power_time = current_time # 更新获取时间
except Exception as e:
logging.error(f"电量获取失败: {str(e)}")
new_power = last_power if last_power else "0%" # 失败时使用缓存值或默认值
else:
new_power = last_power # 未到更新时间,使用缓存值
return new_power
def Bottom_edge(): # 在图片中添加底边内容 def Bottom_edge(): # 在图片中添加底边内容
draw.rectangle((0, 105, 250, 122), 'black', 'black') draw.rectangle((0, 105, 250, 122), 'black', 'black')
'''电池图标画图''' '''电池图标画图'''
@@ -253,24 +274,39 @@ def Partial_refresh(): # 局刷函数
power_str = power_str1 power_str = power_str1
Local_strong_brush() # 局部强刷 Local_strong_brush() # 局部强刷
retry_interval = 180 # 设置重试间隔时间(秒)
while True:
try:
##################屏幕初始化#########################
epd = epd2in13_V4.EPD() #初始化
epd.init()#设定屏幕刷新模式
#epd.Clear(0xFF) #清除屏幕内容
##################屏幕初始化#########################
logging.info("Width = %s, Height = %s", format(epd.width), format(epd.height)) #打印屏幕高度及宽度
logging.info("初始化并清空显示屏")#屏幕开始准备相关展示
info_image = Image.new('1', (epd.height, epd.width), 255) #画布创建准备
draw = ImageDraw.Draw(info_image)
Basic_refresh() #全局刷新
Partial_refresh() #局部刷新
epd.init()
epd.Clear(0xFF)
epd.sleep()
time.sleep(300)
break # 如果脚本执行成功,则退出循环
except (OSError, Exception) as e: # 捕获你提到的异常
logging.error("发生了错误: %s", e)
time.sleep(retry_interval) # 等待一段时间后重试
except KeyboardInterrupt:
logging.info("检测到键盘中断,正在清理并退出")
epd.init()
epd.Clear(0xFF) # 清除屏幕内容
epd.sleep() # 使屏幕进入休眠状态
epd2in13_V4.epdconfig.module_exit() # 清理资源
exit()
try: # 脚本正常结束后的清理操作
##################屏幕初始化######################### epd.init()
epd = epd2in13_V4.EPD() # 初始化 epd.Clear(0xFF) # 清除屏幕内容
epd.init() # 设定屏幕刷新模式 epd.sleep() # 使屏幕进入休眠状态
logging.info("Width = %s, Height = %s", format(epd.width), format(epd.height)) # 打印屏幕高度及宽度 epd2in13_V4.epdconfig.module_exit() # 清理资源
logging.info("初始化并清空显示屏") # 屏幕开始准备相关展示 exit()
info_image = Image.new('1', (epd.height, epd.width), 255) # 画布创建准备
draw = ImageDraw.Draw(info_image)
Basic_refresh() # 全局刷新
Partial_refresh() # 局部刷新
except OSError as e:
logging.info(e)
except KeyboardInterrupt:
logging.info("检测到键盘中断,正在清理并退出")
finally:
epd.init()
epd.Clear(0xFF) # 清除屏幕内容
epd.sleep() # 使屏幕进入休眠状态
epd2in13_V4.epdconfig.module_exit() # 清理资源
exit()

8
bin/requirements.txt Normal file
View File

@@ -0,0 +1,8 @@
borax==4.1.2
certifi==2025.1.31
charset-normalizer==3.4.1
idna==3.10
pillow==11.1.0
requests==2.32.3
spidev==3.6
urllib3==2.3.0

View File

@@ -11,4 +11,4 @@ do
kill -9 $id kill -9 $id
done done
nohup /usr/bin/python3 -u $dir/$f_name > $logdir/info.log 2>&1 & nohup /usr/bin/python3 -u $dir/$f_name > $logdir/info.log 2>&1 &
nohup /usr/bin/python3 -u $dir/$f1_name > $logdir/info-wenter.log 2>&1 & nohup /usr/bin/python3 -u $dir/$f1_name > $logdir/info-weather.log 2>&1 &

BIN
bin/vendor/borax-4.1.2-py3-none-any.whl vendored Normal file

Binary file not shown.

Binary file not shown.

BIN
bin/vendor/idna-3.10-py3-none-any.whl vendored Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
bin/vendor/spidev-3.6.tar.gz vendored Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -7,83 +7,92 @@ import logging
import requests import requests
from threading import Timer from threading import Timer
white = 255 # 颜色 logging.basicConfig(
black = 0 level=logging.INFO,
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s') # 设置日志级别 format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
def get_area_id(city_name): def get_area_id(city_name):
"""从city.js中检索AREAID无限重试直到成功""" """从city.js中检索AREAID无限重试直到成功"""
url = "https://j.i8tq.com/weather2020/search/city.js" url = "https://j.i8tq.com/weather2020/search/city.js"
while True: while True:
try: try:
response = requests.get(url) resp = requests.get(url, timeout=10)
response.raise_for_status() # 检查请求是否成功 resp.encoding = 'utf-8' # 显式设置编码
city_data_text = response.text.strip().split('var city_data = ')[-1].rstrip(';') city_data = json.loads(resp.text.split('=', 1)[1].rstrip(';'))
if city_data_text: for province in city_data.values():
city_data = json.loads(city_data_text) for city in province.values():
for province, cities in city_data.items(): for district, info in city.items():
for city, districts in cities.items(): if info['NAMECN'] == city_name:
for district, info in districts.items(): return info['AREAID']
if info['NAMECN'] == city_name: logging.error("未找到城市: %s", city_name)
return info['AREAID'] except Exception as e:
logging.error("城市名称 '%s' 在城市数据中未找到", city_name) logging.error("获取城市ID失败: %s", str(e))
else: time.sleep(180)
logging.error("从city.js接收到的数据为空")
except (requests.RequestException, json.JSONDecodeError) as e:
logging.error("检索或解析城市数据时发生错误: %s", e)
time.sleep(180) # 重试前等待
def get_current_city(): def get_current_city():
"""获取当前城市名称,无限重试直到成功""" """获取当前定位城市并去除''后缀"""
url = "http://ip-api.com/json/?lang=zh-CN" url = "http://ip-api.com/json/?lang=zh-CN"
while True: while True:
try: try:
response = requests.get(url) resp = requests.get(url, timeout=10)
response.raise_for_status() # 检查请求是否成功 resp.encoding = 'utf-8' # 显式设置编码
data = response.json() data = resp.json()
if data['status'] == 'success': if data['status'] == 'success':
return data['city'] return data['city'].rstrip('')
else: logging.error("定位失败: %s", data.get('message'))
logging.error("获取当前城市失败: %s", data['message']) except Exception as e:
except (requests.RequestException, json.JSONDecodeError) as e: logging.error("定位异常: %s", str(e))
logging.error("检索或解析当前城市时出现错误: %s", e) time.sleep(180)
time.sleep(180) # 重试前等待
def schedule_getWeath(): def schedule_getWeath():
"""调度 getWeath 函数每3分钟执行一次""" """定时任务调度"""
getWeath() try:
Timer(180, schedule_getWeath).start() # 重新设置定时器 getWeath()
finally:
Timer(180, schedule_getWeath).start()
def getWeath(city='101060101'): def getWeath(default_city='101060101'):
"""获取天气数据核心函数"""
city_name = get_current_city()
area_id = default_city # 设置默认值
if city_name:
try:
area_id = get_area_id(city_name) or default_city
except Exception as e:
logging.error("获取区域ID失败: %s", str(e))
headers = { headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Referer': 'https://www.weather.com.cn/' 'Referer': 'https://www.weather.com.cn/'
} }
current_city = get_current_city()
if current_city:
area_id = get_area_id(current_city)
if area_id:
city = area_id
try: try:
response = requests.get(f'https://d1.weather.com.cn/sk_2d/{city}.html', headers=headers) resp = requests.get(
response.raise_for_status() # 检查请求是否成功 f'https://d1.weather.com.cn/sk_2d/{area_id}.html',
response.encoding = 'utf-8' headers=headers,
weather_data = response.text[11:] timeout=15
with open('/root/2.13-Ink-screen-clock/bin/weather.json', 'w') as fileHandle: )
fileHandle.write(weather_data) resp.encoding = 'utf-8' # 关键修改:强制设置响应编码
print("天气文件更新") resp.raise_for_status()
except requests.RequestException as e:
logging.error("获取天气数据时出现网络错误: %s", e) # 直接处理原始字节数据
weather_data = resp.content[11:].decode('utf-8')
# 使用utf-8编码写入文件
with open('/root/2.13-Ink-screen-clock/bin/weather.json', 'w', encoding='utf-8') as f:
f.write(weather_data)
logging.info("天气数据更新成功")
except Exception as e: except Exception as e:
logging.error("发生了意外错误: %s", e) logging.error("天气更新失败: %s", str(e))
try: if __name__ == "__main__":
schedule_getWeath() # 开始调度天气获取函数 try:
except KeyboardInterrupt: schedule_getWeath()
logging.info("检测到键盘中断,正在退出") while True:
except Exception as e: time.sleep(1) # 保持主线程存活
logging.error("发生了意外错误: %s", e) except KeyboardInterrupt:
exit() logging.info("程序已终止")
# 脚本正常结束后的清理操作
exit()