mirror of
https://github.com/kxgx/2.13-Ink-screen-clock.git
synced 2026-03-15 07:03:16 +08:00
Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
caf0228277 | ||
|
|
54b76b4d26 | ||
|
|
f25f0d8dcf | ||
|
|
8f0fd2e6d6 | ||
|
|
7350d120ad | ||
|
|
db8c4344ba | ||
|
|
7759cabcf0 | ||
|
|
a56b337975 | ||
|
|
7cd6136696 | ||
|
|
569852a1dc | ||
|
|
7c48d92bc1 | ||
|
|
9b3afeb323 | ||
|
|
2d3459f3d0 | ||
|
|
c05eb73fb6 | ||
|
|
b9cd0bab9d | ||
|
|
db174e366d | ||
|
|
0c4f04e612 | ||
|
|
a0f636a8d5 | ||
|
|
d0fe962c06 | ||
|
|
8d3bb91ed3 | ||
|
|
9d69de92f2 | ||
|
|
77fef0187e | ||
|
|
19177a14ba | ||
|
|
6d7fdab6e1 | ||
|
|
3842f61add | ||
|
|
f1a2e59e4b | ||
|
|
b8c1df3ee2 | ||
|
|
da6b99e99c | ||
|
|
01ea753627 | ||
|
|
4c3fefa9ff | ||
|
|
c7275aa400 | ||
|
|
a1e9356c83 | ||
|
|
914129a181 |
24
README.md
24
README.md
@@ -1,5 +1,5 @@
|
||||
# 墨水屏展示当前时间及天气数据
|
||||
|
||||
# 此分支专属于本人的个人设备实验分支以及备份
|
||||
本项目复刻自[Seek-Huang](https://github.com/Seek-Huang/2.13-Ink-screen-clock)的代码仓库
|
||||
并在此基础上进行改进
|
||||
|
||||
@@ -66,6 +66,7 @@ sudo reboot
|
||||
--zh 设置系统语言为zh_CN,UTF-8
|
||||
--cn 替换apt镜像源为中国镜像源
|
||||
--gitcn 克隆中国仓库
|
||||
--pip-offline pip依赖离线安装
|
||||
--pisugar-wifi-conf 安装pisugar-wifi-conf
|
||||
--pisugar-power-manager 安装pisugar-power-manager
|
||||
--version <tag> 版本号(使用方法 --version + 仓库标签,格式例如 v1.x.x ,可以是主仓库main)
|
||||
@@ -73,22 +74,29 @@ sudo reboot
|
||||
```
|
||||
###
|
||||
```Bash
|
||||
#中国源默认设置
|
||||
#中国源默认设置(不加参数)
|
||||
curl -sSL https://gitee.com/xingguangk/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash
|
||||
```
|
||||
```Bash
|
||||
#中国源全参数设置(不使用--debug参数)
|
||||
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>
|
||||
#中国源参数设置(不使用--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 --version <tag>
|
||||
```
|
||||
```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
|
||||
```
|
||||
```Bash
|
||||
#默认源全参数设置(不使用--debug参数)
|
||||
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>
|
||||
#默认源默认设置(不使用--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 --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
|
||||
|
||||
149
bin/clock.py
149
bin/clock.py
@@ -20,7 +20,7 @@ if os.path.exists(libdir):
|
||||
logging.debug("Loading Fonts")
|
||||
font01 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 20) #字体文件
|
||||
font02 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15) #字体文件
|
||||
font03 = ImageFont.truetype(os.path.join(picdir, 'DSEG7Modern-Bold.ttf'), 38) #字体文件
|
||||
font03 = ImageFont.truetype(os.path.join(picdir, 'DSEG7Modern-Bold.ttf'), 66) #字体文件
|
||||
font04 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 10) #字体文件
|
||||
font05 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 12) #字体文件
|
||||
font06 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 13) #字体文件
|
||||
@@ -35,11 +35,77 @@ def get_date():#返回当前年月日及星期几
|
||||
today=LunarDate.today()
|
||||
week_day_dict = {0: '星期一',1: '星期二',2: '星期三',3: '星期四',4: '星期五',5: '星期六',6: '星期日',}
|
||||
day = date.weekday()
|
||||
return time.strftime('%Y年%m月%d日')+' '+week_day_dict[day]+' '+today.strftime('农 %M月%D')
|
||||
def get_time():#返回当前时间,不到秒,大写
|
||||
return time.strftime('%H:%M')
|
||||
def Get_address():#获取当前的IP地址
|
||||
return (subprocess.check_output(u"hostname -I | cut -d\' \' -f1 | head --bytes -1", shell = True ).decode('gbk'))
|
||||
return time.strftime('%Y年%m月%d日')+''+week_day_dict[day]+''+today.strftime('农历%M月%D')
|
||||
# 定义一个全局标志变量,用于检查是否已经设置了系统时间或尝试过设置
|
||||
has_set_system_time = False
|
||||
|
||||
def set_system_time_from_hwclock(utc=True):
|
||||
"""Set the system time from the hardware clock.
|
||||
|
||||
Args:
|
||||
utc (bool): Whether the RTC is in UTC. Default is True.
|
||||
"""
|
||||
try:
|
||||
# 记录调用 hwclock 前的时间
|
||||
before_time = datetime.datetime.now()
|
||||
logging.debug(f"System time before hwclock call: {before_time}")
|
||||
|
||||
# 构造 hwclock 命令及其参数
|
||||
hwclock_args = ['sudo', 'hwclock', '--hctosys']
|
||||
if not utc:
|
||||
hwclock_args.append('--localtime')
|
||||
|
||||
logging.debug(f"Executing hwclock command: {' '.join(hwclock_args)}")
|
||||
|
||||
# 使用 subprocess.run 执行 hwclock --hctosys 并捕获输出
|
||||
result = subprocess.run(hwclock_args,
|
||||
check=True, # 如果命令失败,则抛出 CalledProcessError 异常
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True)
|
||||
|
||||
# 等待一小段时间以确保时间更新完成
|
||||
time.sleep(0.1) # 根据需要调整
|
||||
|
||||
# 记录调用 hwclock 后的时间
|
||||
after_time = datetime.datetime.now()
|
||||
logging.debug("System time successfully set from hardware clock.")
|
||||
logging.debug(f"System time after hwclock call: {after_time}")
|
||||
|
||||
# 检查时间是否发生了倒退
|
||||
if after_time < before_time:
|
||||
logging.warning(f"Time went backwards after hwclock call: before={before_time}, after={after_time}")
|
||||
|
||||
return True
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.error(f"Failed to set system time from hardware clock: {e.stderr}")
|
||||
return False
|
||||
except Exception as e:
|
||||
logging.error(f"An unexpected error occurred: {str(e)}")
|
||||
return False
|
||||
|
||||
def get_time():
|
||||
global has_set_system_time
|
||||
|
||||
if not has_set_system_time:
|
||||
# 尝试从硬件时钟设置系统时间,默认假设 RTC 是 UTC
|
||||
success = set_system_time_from_hwclock(utc=True)
|
||||
# 无论成功与否,都更新标志变量以避免重复尝试
|
||||
has_set_system_time = True
|
||||
|
||||
# 获取并返回当前时间,格式为 HH:MM 大写
|
||||
current_time = time.strftime('%H:%M').upper()
|
||||
logging.debug(f"Returning current time: {current_time}")
|
||||
return current_time
|
||||
def Get_ipv4_address(): # 获取当前的IP地址
|
||||
try:
|
||||
ip_output = subprocess.check_output(
|
||||
"hostname -I | grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}'", shell=True).decode('utf-8').strip()
|
||||
ip_list = ip_output.split()
|
||||
filtered_ips = [ip for ip in ip_list if not ip.startswith("172.")]
|
||||
return filtered_ips[0] if filtered_ips else "地址获取失败"
|
||||
except subprocess.CalledProcessError:
|
||||
return "获取失败"
|
||||
def CPU_temperature():#CPU温度获取
|
||||
temperatura = os.popen('vcgencmd measure_temp').readline()
|
||||
temperatura = temperatura.replace('temp=','').strip()
|
||||
@@ -70,7 +136,7 @@ def Bottom_edge(): #在图片中添加底边内容
|
||||
draw.line((199,109,199,114),fill=255, width=1)
|
||||
draw.line((200,114,204,114),fill=255, width=1)
|
||||
global local_addr #获取当前IP地址
|
||||
local_addr= Get_address() #获取当前IP地址
|
||||
local_addr= Get_ipv4_address() #获取当前IP地址
|
||||
draw.text((10,107),"IP:"+local_addr,font = font05,fill =255)#显示当前IP地址
|
||||
def Basic_refresh(): #全刷函数
|
||||
logging.info("Refresh and prepare the basic content before starting the canvas")#开始画布前刷新准备基础内容
|
||||
@@ -94,8 +160,8 @@ def Partial_refresh():#局刷函数
|
||||
global local_time
|
||||
local_time1=get_time()
|
||||
if (local_time1==local_time) ==False:
|
||||
draw.rectangle((5, 40, 133, 82), fill = 255) #时间局刷区域
|
||||
draw.text((5,40),local_time1,font = font03,fill =0)#刷新当前时间
|
||||
draw.rectangle((5, 17, 133, 95), fill = 255) #时间局刷区域
|
||||
draw.text((5,17),local_time1,font = font03,fill =0)#刷新当前时间
|
||||
local_time=local_time1
|
||||
Local_strong_brush() #局部强刷
|
||||
get_date_var1=get_date() #局刷判断,如果时间与前一次不一致说明内容变化,需要刷新显示
|
||||
@@ -107,7 +173,7 @@ def Partial_refresh():#局刷函数
|
||||
logging.debug("头部日期部位发生刷新变化.")
|
||||
Local_strong_brush() #局部强刷
|
||||
global local_addr #当前IP地址
|
||||
local_addr1 = Get_address()
|
||||
local_addr1 = Get_ipv4_address()
|
||||
if (local_addr1==local_addr) ==False:
|
||||
draw.rectangle((1, 107, 94, 120), fill = 0) #设置头部刷新区域
|
||||
draw.text((10,107),"IP:"+local_addr1,font = font05,fill =255)#显示当前IP地址
|
||||
@@ -116,40 +182,37 @@ def Partial_refresh():#局刷函数
|
||||
#显示当前电量百分比
|
||||
power_str=power_str1
|
||||
Local_strong_brush() #局部强刷
|
||||
logging.info("电源电量局部刷新")
|
||||
try:
|
||||
##################屏幕初始化#########################
|
||||
getWeath()#天气获取函数开始运行
|
||||
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()
|
||||
logging.debug("电源电量局部刷新")
|
||||
|
||||
except Exception as e:
|
||||
logging.error("An unexpected error occurred: %s", e)
|
||||
epd.init()
|
||||
epd.Clear(0xFF) # 清除屏幕内容
|
||||
epd.sleep() # 使屏幕进入休眠状态
|
||||
epd2in13_V4.epdconfig.module_exit() # 清理资源
|
||||
exit()
|
||||
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()
|
||||
|
||||
# 脚本正常结束后的清理操作
|
||||
epd.init()
|
||||
|
||||
@@ -18,6 +18,8 @@ USE_CN_GIT=false
|
||||
USE_PISUGAR_WIFI_CONF=false
|
||||
# 检查是否安装pisugar-power-manager
|
||||
USE_PISUGAR_POWER_MANAGER=false
|
||||
# 检查是否使用离线安装pip依赖
|
||||
USE_OFFLINE_PIP=false
|
||||
|
||||
# 解析命令行参数
|
||||
while [ "$#" -gt 0 ]; do
|
||||
@@ -31,6 +33,9 @@ while [ "$#" -gt 0 ]; do
|
||||
--gitcn)
|
||||
USE_CN_GIT=true
|
||||
;;
|
||||
--pip-offline)
|
||||
USE_OFFLINE_PIP=true
|
||||
;;
|
||||
--pisugar-wifi-conf)
|
||||
USE_PISUGAR_WIFI_CONF=true
|
||||
;;
|
||||
@@ -203,23 +208,7 @@ install_packages() {
|
||||
fi
|
||||
}
|
||||
|
||||
# 安装pip包函数
|
||||
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"
|
||||
|
||||
install_Ink-screen-clock() {
|
||||
# 检查墨水屏时钟仓库是否存在
|
||||
if [ ! -d "$HOME/2.13-Ink-screen-clock" ]; then
|
||||
echo "正在克隆仓库"
|
||||
@@ -234,6 +223,41 @@ setup_service() {
|
||||
else
|
||||
echo "仓库文件夹已存在,跳过克隆"
|
||||
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
|
||||
@@ -306,6 +330,7 @@ if [ -f /etc/debian_version ]; then
|
||||
echo "执行Debian 11 (Bullseye) 相关操作"
|
||||
update_sources_list "bullseye"
|
||||
install_packages
|
||||
install_Ink-screen-clock
|
||||
install_pip_packages
|
||||
setup_service
|
||||
#install_webui
|
||||
@@ -316,6 +341,7 @@ if [ -f /etc/debian_version ]; then
|
||||
echo "执行Debian 12 (Bookworm) 相关操作"
|
||||
update_sources_list "bookworm"
|
||||
install_packages
|
||||
install_Ink-screen-clock
|
||||
install_pip_packages
|
||||
setup_service
|
||||
#install_webui
|
||||
|
||||
203
bin/main.py
203
bin/main.py
@@ -21,53 +21,124 @@ if os.path.exists(libdir):
|
||||
from waveshare_epd import epd2in13_V4 #引入墨水屏驱动文件
|
||||
logging.debug("Loading Fonts")
|
||||
font01 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 20) #字体文件
|
||||
font02 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 15) #字体文件
|
||||
font03 = ImageFont.truetype(os.path.join(picdir, 'DSEG7Modern-Bold.ttf'), 38) #字体文件
|
||||
font02 = ImageFont.truetype(os.path.join(picdir, 'GB2312.ttf'), 15) #字体文件
|
||||
font03 = ImageFont.truetype(os.path.join(picdir, 'Fonttt.ttf'), 48) #字体文件
|
||||
font04 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 10) #字体文件
|
||||
font05 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 12) #字体文件
|
||||
font06 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 13) #字体文件
|
||||
font06 = ImageFont.truetype(os.path.join(picdir, '原神cn.ttf'), 13) #字体文件
|
||||
################################引入配置文件结束################################################
|
||||
def Local_strong_brush(): #局部强制刷新显示
|
||||
i = 0
|
||||
while i < 5:
|
||||
epd.displayPartial(epd.getbuffer(info_image.rotate(180)))#局刷开始
|
||||
i = i + 1
|
||||
def get_date():#返回当前年月日及星期几
|
||||
def get_date(): # 返回当前年月日及星期几
|
||||
date = datetime.datetime.now()
|
||||
today=LunarDate.today()
|
||||
week_day_dict = {0: '星期一',1: '星期二',2: '星期三',3: '星期四',4: '星期五',5: '星期六',6: '星期日',}
|
||||
today = LunarDate.today()
|
||||
week_day_dict = {0: '星期一', 1: '星期二', 2: '星期三', 3: '星期四', 4: '星期五', 5: '星期六', 6: '星期日'}
|
||||
day = date.weekday()
|
||||
return time.strftime('%Y年%m月%d日')+''+week_day_dict[day]+''+today.strftime('农历%M月%D')
|
||||
def get_time():#返回当前时间,不到秒,大写
|
||||
return time.strftime('%H:%M')
|
||||
def Get_address():#获取当前的IP地址
|
||||
return (subprocess.check_output(u"hostname -I | cut -d\' \' -f1 | head --bytes -1", shell = True ).decode('gbk'))
|
||||
return f"{date.strftime('%Y年%m月%d日')}{week_day_dict[day]}{today.strftime('农历%M月%D')}"
|
||||
|
||||
# 定义一个全局标志变量,用于检查是否已经设置了系统时间或尝试过设置
|
||||
has_set_system_time = False
|
||||
|
||||
def set_system_time_from_hwclock(utc=True):
|
||||
"""Set the system time from the hardware clock.
|
||||
|
||||
Args:
|
||||
utc (bool): Whether the RTC is in UTC. Default is True.
|
||||
"""
|
||||
try:
|
||||
# 记录调用 hwclock 前的时间
|
||||
before_time = datetime.datetime.now()
|
||||
logging.debug(f"System time before hwclock call: {before_time}")
|
||||
|
||||
# 构造 hwclock 命令及其参数
|
||||
hwclock_args = ['sudo', 'hwclock', '--hctosys']
|
||||
if not utc:
|
||||
hwclock_args.append('--localtime')
|
||||
|
||||
logging.debug(f"Executing hwclock command: {' '.join(hwclock_args)}")
|
||||
|
||||
# 使用 subprocess.run 执行 hwclock --hctosys 并捕获输出
|
||||
result = subprocess.run(hwclock_args,
|
||||
check=True, # 如果命令失败,则抛出 CalledProcessError 异常
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True)
|
||||
|
||||
# 等待一小段时间以确保时间更新完成
|
||||
time.sleep(0.1) # 根据需要调整
|
||||
|
||||
# 记录调用 hwclock 后的时间
|
||||
after_time = datetime.datetime.now()
|
||||
logging.debug("System time successfully set from hardware clock.")
|
||||
logging.debug(f"System time after hwclock call: {after_time}")
|
||||
|
||||
# 检查时间是否发生了倒退
|
||||
if after_time < before_time:
|
||||
logging.warning(f"Time went backwards after hwclock call: before={before_time}, after={after_time}")
|
||||
|
||||
return True
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.error(f"Failed to set system time from hardware clock: {e.stderr}")
|
||||
return False
|
||||
except Exception as e:
|
||||
logging.error(f"An unexpected error occurred: {str(e)}")
|
||||
return False
|
||||
|
||||
def get_time():
|
||||
global has_set_system_time
|
||||
|
||||
if not has_set_system_time:
|
||||
# 尝试从硬件时钟设置系统时间,默认假设 RTC 是 UTC
|
||||
success = set_system_time_from_hwclock(utc=True)
|
||||
# 无论成功与否,都更新标志变量以避免重复尝试
|
||||
has_set_system_time = True
|
||||
|
||||
# 获取并返回当前时间,格式为 HH:MM 大写
|
||||
current_time = time.strftime('%H:%M').upper()
|
||||
logging.debug(f"Returning current time: {current_time}")
|
||||
return current_time
|
||||
def Get_ipv4_address(): # 获取当前的IP地址
|
||||
try:
|
||||
# 执行命令获取IP地址,并处理输出以仅返回IPv4地址
|
||||
ip_output = subprocess.check_output("hostname -I | grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}'", shell=True).decode('utf-8').strip()
|
||||
# 分割输出以获取单个IP地址列表
|
||||
ip_output = subprocess.check_output(
|
||||
"hostname -I | grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}'", shell=True).decode('utf-8').strip()
|
||||
ip_list = ip_output.split()
|
||||
# 过滤掉以172开头的IP地址
|
||||
filtered_ips = [ip for ip in ip_list if not ip.startswith("172.")]
|
||||
# 如果有有效的IP地址,返回第一个,否则返回获取失败
|
||||
if filtered_ips:
|
||||
return filtered_ips[0]
|
||||
else:
|
||||
return "地址获取失败"
|
||||
except subprocess.CalledProcessError as e:
|
||||
logging.error("获取IPv4地址失败: %s", e)
|
||||
return filtered_ips[0] if filtered_ips else "地址获取失败"
|
||||
except subprocess.CalledProcessError:
|
||||
return "获取失败"
|
||||
def CPU_temperature():#CPU温度获取
|
||||
temperatura = os.popen('vcgencmd measure_temp').readline()
|
||||
temperatura = temperatura.replace('temp=','').strip()
|
||||
return str(temperatura)
|
||||
def Memory_footprint():#显示内存占用百分比
|
||||
return(subprocess.check_output(u"free -m | awk -F '[ :]+' 'NR==2{printf \"%d\", ($3)/$2*100}'", shell = True ).decode('gbk'))
|
||||
def CPU_usage(): #显示CPU占用百分比
|
||||
return(str(int(float(os.popen("top -b -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))))
|
||||
def power_battery():#获取当前电池电量
|
||||
return(str(int(subprocess.check_output(u"echo \"get battery\" | nc -q 0 127.0.0.1 8423|awk -F':' '{print int($2)}'", shell = True ).decode('gbk')))+u'%')
|
||||
# 全局变量声明
|
||||
last_power = None # 用于存储上一次获取的电量值
|
||||
last_power_time = 0 # 用于存储上一次获取电量的时间戳
|
||||
|
||||
def power_battery(): # 获取当前电池电量
|
||||
global last_power, last_power_time
|
||||
current_time = time.time() # 获取当前时间戳
|
||||
|
||||
# 每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
|
||||
# 打印电量信息
|
||||
print(power_battery())
|
||||
def Bottom_edge(): #在图片中添加底边内容
|
||||
@@ -126,7 +197,7 @@ def Basic_refresh(): #全刷函数
|
||||
draw.text((2,2),get_date_var,font = font02,fill =0)#将日期及星期几显示到屏幕
|
||||
global local_time
|
||||
local_time=get_time()
|
||||
draw.text((5,40),local_time,font = font03,fill =0)#显示当前时间
|
||||
draw.text((5,28),local_time,font = font03,fill =0)#显示当前时间
|
||||
Bottom_edge() #添加底边内容
|
||||
Weather() #天气内容
|
||||
epd.display(epd.getbuffer(info_image.rotate(180)))
|
||||
@@ -142,8 +213,8 @@ def Partial_refresh():#局刷函数
|
||||
global local_time
|
||||
local_time1=get_time()
|
||||
if (local_time1==local_time) ==False:
|
||||
draw.rectangle((5, 40, 133, 82), fill = 255) #时间局刷区域
|
||||
draw.text((5,40),local_time1,font = font03,fill =0)#刷新当前时间
|
||||
draw.rectangle((5, 28, 149, 82), fill = 255) #时间局刷区域
|
||||
draw.text((5,28),local_time1,font = font03,fill =0)#刷新当前时间
|
||||
local_time=local_time1
|
||||
Local_strong_brush() #局部强刷
|
||||
get_date_var1=get_date() #局刷判断,如果时间与前一次不一致说明内容变化,需要刷新显示
|
||||
@@ -218,39 +289,37 @@ def Partial_refresh():#局刷函数
|
||||
draw.text((129,108),power_battery(),font = font04,fill =255) #显示当前电量百分比
|
||||
power_str=power_str1
|
||||
Local_strong_brush() #局部强刷
|
||||
# logging.info("电源电量局部刷新")
|
||||
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()
|
||||
except OSError as e:
|
||||
logging.info(e)
|
||||
except KeyboardInterrupt:
|
||||
logging.info("检测到键盘中断,正在清理并退出")
|
||||
epd.init()
|
||||
epd.Clear(0xFF) # 清除屏幕内容
|
||||
epd.sleep() # 使屏幕进入休眠状态
|
||||
epd2in13_V4.epdconfig.module_exit() # 清理资源
|
||||
exit()
|
||||
# logging.info("电池电量局部刷新")
|
||||
|
||||
except Exception as e:
|
||||
logging.error("发生了意外的错误: %s", e)
|
||||
epd.init()
|
||||
epd.Clear(0xFF) # 清除屏幕内容
|
||||
epd.sleep() # 使屏幕进入休眠状态
|
||||
epd2in13_V4.epdconfig.module_exit() # 清理资源
|
||||
exit()
|
||||
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()
|
||||
|
||||
# 脚本正常结束后的清理操作
|
||||
epd.init()
|
||||
|
||||
258
bin/main.py1
Normal file
258
bin/main.py1
Normal file
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding:utf-8 -*-
|
||||
from PIL import Image,ImageDraw,ImageFont #引入图片处理库
|
||||
import os,sys,re,json,time,datetime #引入系统相关库
|
||||
from borax.calendars.lunardate import LunarDate #农历日期以及天干地支纪年法的 Python 库
|
||||
import logging #日志库
|
||||
import subprocess
|
||||
import os
|
||||
from threading import Timer
|
||||
import requests
|
||||
import socket
|
||||
|
||||
white = 255 #颜色
|
||||
black = 0
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
|
||||
################################引入配置文件开始################################################
|
||||
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
|
||||
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
|
||||
if os.path.exists(libdir):
|
||||
sys.path.append(libdir)#将引入文件添加到环境变量
|
||||
from waveshare_epd import epd2in13_V4 #引入墨水屏驱动文件
|
||||
logging.debug("Loading Fonts")
|
||||
font01 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 20) #字体文件
|
||||
font02 = ImageFont.truetype(os.path.join(picdir, 'GB2312.ttf'), 15) #字体文件
|
||||
font03 = ImageFont.truetype(os.path.join(picdir, 'Fonttt.ttf'), 48) #字体文件
|
||||
font04 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 10) #字体文件
|
||||
font05 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 12) #字体文件
|
||||
font06 = ImageFont.truetype(os.path.join(picdir, '原神cn.ttf'), 13) #字体文件
|
||||
################################引入配置文件结束################################################
|
||||
def Local_strong_brush(): #局部强制刷新显示
|
||||
i = 0
|
||||
while i < 5:
|
||||
epd.displayPartial(epd.getbuffer(info_image.rotate(180)))#局刷开始
|
||||
i = i + 1
|
||||
def get_date():#返回当前年月日及星期几
|
||||
date = datetime.datetime.now()
|
||||
today=LunarDate.today()
|
||||
week_day_dict = {0: '星期一',1: '星期二',2: '星期三',3: '星期四',4: '星期五',5: '星期六',6: '星期日',}
|
||||
day = date.weekday()
|
||||
return time.strftime('%Y年%m月%d日')+''+week_day_dict[day]+''+today.strftime('农历%M月%D')
|
||||
def get_time():#返回当前时间,不到秒,大写
|
||||
return time.strftime('%H:%M')
|
||||
def Get_address():#获取当前的IP地址
|
||||
return (subprocess.check_output(u"hostname -I | cut -d\' \' -f1 | head --bytes -1", shell = True ).decode('gbk'))
|
||||
def Get_ipv4_address(): # 获取当前的IP地址
|
||||
try:
|
||||
# 执行命令获取IP地址,并处理输出以仅返回IPv4地址
|
||||
ip_output = subprocess.check_output("hostname -I | grep -oE '[0-9]{1,3}(\.[0-9]{1,3}){3}'", shell=True).decode('utf-8').strip()
|
||||
# 分割输出以获取单个IP地址列表
|
||||
ip_list = ip_output.split()
|
||||
# 过滤掉以172开头的IP地址
|
||||
filtered_ips = [ip for ip in ip_list if not ip.startswith("172.")]
|
||||
# 如果有有效的IP地址,返回第一个,否则返回获取失败
|
||||
if filtered_ips:
|
||||
return filtered_ips[0]
|
||||
else:
|
||||
return "地址获取失败"
|
||||
except subprocess.CalledProcessError as e:
|
||||
#logging.error("获取IPv4地址失败: %s", e)
|
||||
return "获取失败"
|
||||
def CPU_temperature():#CPU温度获取
|
||||
temperatura = os.popen('vcgencmd measure_temp').readline()
|
||||
temperatura = temperatura.replace('temp=','').strip()
|
||||
return str(temperatura)
|
||||
def Memory_footprint():#显示内存占用百分比
|
||||
return(subprocess.check_output(u"free -m | awk -F '[ :]+' 'NR==2{printf \"%d\", ($3)/$2*100}'", shell = True ).decode('gbk'))
|
||||
def CPU_usage(): #显示CPU占用百分比
|
||||
return(str(int(float(os.popen("top -b -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))))
|
||||
def power_battery():#获取当前电池电量
|
||||
return(str(int(subprocess.check_output(u"echo \"get battery\" | nc -q 0 127.0.0.1 8423|awk -F':' '{print int($2)}'", shell = True ).decode('gbk')))+u'%')
|
||||
# 打印电量信息
|
||||
print(power_battery())
|
||||
def Bottom_edge(): #在图片中添加底边内容
|
||||
draw.rectangle((0, 105, 250, 122), 'black', 'black')
|
||||
'''电池图标画图'''
|
||||
draw.line((126,109,154,109),fill=255, width=1) #电池顶边
|
||||
draw.line((126,110,126,119),fill=255, width=1) #电池左边
|
||||
draw.line((127,119,154,119),fill=255, width=1) #电池下边
|
||||
draw.line((154,110,154,118),fill=255, width=1)
|
||||
draw.line((155,112,157,112),fill=255, width=1)
|
||||
draw.line((155,116,157,116),fill=255, width=1)
|
||||
draw.line((157,113,157,115),fill=255, width=1)
|
||||
global power_str
|
||||
power_str=power_battery()
|
||||
draw.text((129,108),power_str,font = font04,fill =255) #显示当前电量百分比
|
||||
'''电池图标画图'''
|
||||
draw.ellipse((192, 107, 207, 120), 0, 255)# 时钟图标
|
||||
draw.line((199,109,199,114),fill=255, width=1)
|
||||
draw.line((200,114,204,114),fill=255, width=1)
|
||||
global local_addr #获取当前IP地址
|
||||
local_addr= Get_ipv4_address() #获取当前IP地址
|
||||
draw.text((10,107),"IP:"+local_addr,font = font05,fill =255)#显示当前IP地址
|
||||
def Weather(): #在图片中添加天气内容
|
||||
Weather_json = open('/root/2.13-Ink-screen-clock/bin/weather.json','r')
|
||||
Weather_data = Weather_json.read()
|
||||
Weather_json.close()
|
||||
Weather_text=json.loads(Weather_data)
|
||||
global Weather_position
|
||||
global temperature
|
||||
global weather
|
||||
global wind_direction
|
||||
global weather_update
|
||||
global weather_date
|
||||
global humidity
|
||||
Weather_position = Weather_text['cityname'] #定位位置
|
||||
temperature=Weather_text['temp']+u'°C' #温度
|
||||
weather = Weather_text['weather'] #天气情况
|
||||
wind_direction = Weather_text['WD'] #风向
|
||||
weather_update = Weather_text['time'] #天气更新时间
|
||||
weather_date = Weather_text['date'] #日期
|
||||
humidity = Weather_text['SD'] #湿度
|
||||
draw.text((150,25),"天气:",font = font06,fill =0)#显示当前天气前缀
|
||||
draw.text((150,45),"温度:",font = font06,fill =0)#显示当前温度前缀
|
||||
draw.text((150,65),"湿度:",font = font06,fill =0)#显示当前湿度前缀
|
||||
draw.text((150,85),"城市:",font = font06,fill =0)#显示当前城市前缀
|
||||
draw.text((191,25),weather,font = font06,fill =0)
|
||||
draw.text((191,45),temperature,font = font06,fill =0)
|
||||
draw.text((191,65),humidity,font = font06,fill =0)
|
||||
draw.text((191,85),Weather_position,font = font06,fill =0)
|
||||
draw.text((211,107),weather_update,font = font05,fill =255) #显示天气更新时间
|
||||
|
||||
def Basic_refresh(): #全刷函数
|
||||
logging.info("在启动画布之前,刷新并准备基本内容")#开始画布前刷新准备基础内容
|
||||
global get_date_var
|
||||
get_date_var=get_date() #记录开始数据
|
||||
draw.text((2,2),get_date_var,font = font02,fill =0)#将日期及星期几显示到屏幕
|
||||
global local_time
|
||||
local_time=get_time()
|
||||
draw.text((5,28),local_time,font = font03,fill =0)#显示当前时间
|
||||
Bottom_edge() #添加底边内容
|
||||
Weather() #天气内容
|
||||
epd.display(epd.getbuffer(info_image.rotate(180)))
|
||||
def Partial_full_brush(): #局部定时全刷函数
|
||||
Basic_refresh() #全局刷新
|
||||
logging.debug("局部定时全局刷新")
|
||||
epd.init()
|
||||
def Partial_refresh():#局刷函数
|
||||
logging.info("部分内容更新,此更新建议与分钟同步,以节省墨水屏的使用寿命")#局部内容更新,此更新建议与分钟同步,以节省墨水屏寿命
|
||||
epd.displayPartBaseImage(epd.getbuffer(info_image.rotate(180)))
|
||||
epd.init()
|
||||
while (True):
|
||||
global local_time
|
||||
local_time1=get_time()
|
||||
if (local_time1==local_time) ==False:
|
||||
draw.rectangle((5, 28, 149, 82), fill = 255) #时间局刷区域
|
||||
draw.text((5,28),local_time1,font = font03,fill =0)#刷新当前时间
|
||||
local_time=local_time1
|
||||
Local_strong_brush() #局部强刷
|
||||
get_date_var1=get_date() #局刷判断,如果时间与前一次不一致说明内容变化,需要刷新显示
|
||||
global get_date_var #再次声明这个是全局变量
|
||||
if(get_date_var1==get_date_var) ==False:
|
||||
draw.rectangle((2, 2, 250, 16), fill = 255) #设置头部刷新区域
|
||||
draw.text((2,2),get_date_var1,font = font02,fill =0)#将日期及星期几刷新显示到屏幕
|
||||
get_date_var=get_date_var1 #将更新的值保存到初始变量,直到下一次变化时执行该刷新操作
|
||||
logging.debug("头部日期部位发生刷新变化.")
|
||||
Local_strong_brush() #局部强刷
|
||||
global local_addr #当前IP地址
|
||||
local_addr1 = Get_ipv4_address()
|
||||
if (local_addr1==local_addr) ==False:
|
||||
draw.rectangle((1, 107, 123, 120), fill = 0) #设置头部刷新区域
|
||||
draw.text((10,107),"IP:"+local_addr1,font = font05,fill =255)#显示当前IP地址
|
||||
local_addr=local_addr1
|
||||
Local_strong_brush() #局部强刷
|
||||
'''天气局部更新函数'''
|
||||
Weather_json = open('/root/2.13-Ink-screen-clock/bin/weather.json','r')
|
||||
Weather_data = Weather_json.read()
|
||||
Weather_json.close()
|
||||
Weather_text=json.loads(Weather_data)
|
||||
global Weather_position
|
||||
global temperature
|
||||
global weather
|
||||
global wind_direction
|
||||
global weather_update
|
||||
global weather_date
|
||||
global humidity
|
||||
Weather_position1 = Weather_text['cityname'] #定位位置
|
||||
temperature1=Weather_text['temp']+u'°C' #温度
|
||||
weather11 = Weather_text['weather'] #天气情况
|
||||
wind_direction1 = Weather_text['WD'] #风向
|
||||
weather_update1 = Weather_text['time'] #天气更新时间
|
||||
weather_date1 = Weather_text['date'] #日期
|
||||
humidity1 = Weather_text['SD'] #湿度
|
||||
if (weather11==weather) ==False:
|
||||
draw.rectangle((191, 25, 249, 38), fill = 255) #天气局刷区域
|
||||
draw.text((191,25),weather11,font = font06,fill =0)
|
||||
weather=weather11
|
||||
logging.info("天气局部刷新")
|
||||
Local_strong_brush() #局部强刷
|
||||
if (temperature1==temperature) ==False:
|
||||
draw.rectangle((191, 45, 249, 57), fill = 255) #局刷区域
|
||||
draw.text((191,45),temperature1,font = font06,fill =0)
|
||||
temperature=temperature1
|
||||
logging.info("温度局部刷新")
|
||||
Local_strong_brush() #局部强刷
|
||||
if (humidity1==humidity) ==False:
|
||||
draw.rectangle((191, 65, 249, 77), fill = 255) #局刷区域
|
||||
draw.text((191,65),humidity1,font = font06,fill =0)
|
||||
humidity = humidity1
|
||||
logging.info("湿度局部刷新")
|
||||
Local_strong_brush() #局部强刷
|
||||
if (Weather_position1==Weather_position) ==False:
|
||||
draw.rectangle((191, 85, 249, 98), fill = 255) #局刷区域
|
||||
draw.text((191,85),Weather_position1,font = font06,fill =0)
|
||||
Weather_position = Weather_position1
|
||||
logging.info("城市局部刷新")
|
||||
Local_strong_brush() #局部强刷
|
||||
if (weather_update1==weather_update) ==False:
|
||||
draw.rectangle((211, 107, 248, 118), fill = 0) #设置更新时间刷新区域
|
||||
draw.text((211,107),weather_update1,font = font05,fill =255) #显示天气更新时间
|
||||
weather_update=weather_update1
|
||||
logging.info("天气更新时间局部刷新")
|
||||
Local_strong_brush() #局部强刷
|
||||
'''天气局部更新函数'''
|
||||
global power_str
|
||||
power_str1 =power_battery()
|
||||
if (power_str1==power_str) ==False:
|
||||
draw.rectangle((128, 110, 153, 117), fill = 0) #设置更新时间刷新区域
|
||||
draw.text((129,108),power_battery(),font = font04,fill =255) #显示当前电量百分比
|
||||
power_str=power_str1
|
||||
Local_strong_brush() #局部强刷
|
||||
# logging.info("电池电量局部刷新")
|
||||
|
||||
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()
|
||||
|
||||
# 脚本正常结束后的清理操作
|
||||
epd.init()
|
||||
epd.Clear(0xFF) # 清除屏幕内容
|
||||
epd.sleep() # 使屏幕进入休眠状态
|
||||
epd2in13_V4.epdconfig.module_exit() # 清理资源
|
||||
exit()
|
||||
8
bin/requirements.txt
Normal file
8
bin/requirements.txt
Normal 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
|
||||
@@ -11,4 +11,4 @@ do
|
||||
kill -9 $id
|
||||
done
|
||||
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
BIN
bin/vendor/borax-4.1.2-py3-none-any.whl
vendored
Normal file
Binary file not shown.
BIN
bin/vendor/certifi-2025.1.31-py3-none-any.whl
vendored
Normal file
BIN
bin/vendor/certifi-2025.1.31-py3-none-any.whl
vendored
Normal file
Binary file not shown.
BIN
bin/vendor/charset_normalizer-3.4.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
vendored
Normal file
BIN
bin/vendor/charset_normalizer-3.4.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
vendored
Normal file
Binary file not shown.
BIN
bin/vendor/idna-3.10-py3-none-any.whl
vendored
Normal file
BIN
bin/vendor/idna-3.10-py3-none-any.whl
vendored
Normal file
Binary file not shown.
BIN
bin/vendor/pillow-11.1.0-cp39-cp39-manylinux_2_28_aarch64.whl
vendored
Normal file
BIN
bin/vendor/pillow-11.1.0-cp39-cp39-manylinux_2_28_aarch64.whl
vendored
Normal file
Binary file not shown.
BIN
bin/vendor/requests-2.32.3-py3-none-any.whl
vendored
Normal file
BIN
bin/vendor/requests-2.32.3-py3-none-any.whl
vendored
Normal file
Binary file not shown.
BIN
bin/vendor/spidev-3.6.tar.gz
vendored
Normal file
BIN
bin/vendor/spidev-3.6.tar.gz
vendored
Normal file
Binary file not shown.
BIN
bin/vendor/urllib3-2.3.0-py3-none-any.whl
vendored
Normal file
BIN
bin/vendor/urllib3-2.3.0-py3-none-any.whl
vendored
Normal file
Binary file not shown.
149
bin/weather.py
149
bin/weather.py
@@ -1,103 +1,98 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding:utf-8 -*-
|
||||
import os, sys, re, json, time, datetime
|
||||
import logging
|
||||
import subprocess
|
||||
import os
|
||||
from threading import Timer
|
||||
import json
|
||||
import time
|
||||
import logging
|
||||
import requests
|
||||
from threading import Timer
|
||||
|
||||
white = 255 # 颜色
|
||||
black = 0
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s') # 设置日志级别
|
||||
|
||||
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
|
||||
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
|
||||
if os.path.exists(libdir):
|
||||
sys.path.append(libdir) # 将引入文件添加到环境变量
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
def get_area_id(city_name):
|
||||
"""从city.js中检索AREAID,无限重试直到成功"""
|
||||
url = "https://j.i8tq.com/weather2020/search/city.js"
|
||||
while True:
|
||||
try:
|
||||
response = requests.get(url)
|
||||
response.raise_for_status() # 检查请求是否成功
|
||||
# 直接打印原始数据
|
||||
logging.debug("Raw data from city.js: %s", response.text)
|
||||
# 预处理返回的数据,去除非JSON部分
|
||||
city_data_text = response.text.strip()
|
||||
city_data_text = city_data_text.split('var city_data = ')[-1].rstrip(';')
|
||||
if city_data_text:
|
||||
city_data = json.loads(city_data_text)
|
||||
# 遍历数据结构,查找城市名称
|
||||
for province, cities in city_data.items():
|
||||
for city, districts in cities.items():
|
||||
for district, info in districts.items():
|
||||
if info['NAMECN'] == city_name:
|
||||
return info['AREAID']
|
||||
logging.error("城市名称 '%s' 在城市数据中未找到,将使用默认城市信息", city_name)
|
||||
else:
|
||||
logging.error("从city.js接收到的数据为空")
|
||||
except (requests.RequestException, json.JSONDecodeError) as e:
|
||||
logging.error("检索或解析城市数据时发生错误: %s", e)
|
||||
time.sleep(180) # 重试前等待
|
||||
resp = requests.get(url, timeout=10)
|
||||
resp.encoding = 'utf-8' # 显式设置编码
|
||||
city_data = json.loads(resp.text.split('=', 1)[1].rstrip(';'))
|
||||
for province in city_data.values():
|
||||
for city in province.values():
|
||||
for district, info in city.items():
|
||||
if info['NAMECN'] == city_name:
|
||||
return info['AREAID']
|
||||
logging.error("未找到城市: %s", city_name)
|
||||
except Exception as e:
|
||||
logging.error("获取城市ID失败: %s", str(e))
|
||||
time.sleep(180)
|
||||
|
||||
def get_current_city():
|
||||
"""获取当前城市名称,无限重试直到成功"""
|
||||
"""获取当前定位城市并去除'市'后缀"""
|
||||
url = "http://ip-api.com/json/?lang=zh-CN"
|
||||
while True:
|
||||
try:
|
||||
response = requests.get(url)
|
||||
response.raise_for_status() # 检查请求是否成功
|
||||
data = response.json()
|
||||
resp = requests.get(url, timeout=10)
|
||||
resp.encoding = 'utf-8' # 显式设置编码
|
||||
data = resp.json()
|
||||
if data['status'] == 'success':
|
||||
return data['city']
|
||||
else:
|
||||
logging.error("获取当前城市失败: %s", data['message'])
|
||||
except (requests.RequestException, json.JSONDecodeError) as e:
|
||||
logging.error("检索或解析当前城市时出现错误: %s", e)
|
||||
time.sleep(180) # 重试前等待
|
||||
# 注意:无限重试可能会在特定情况下导致程序无法终止,请确保在实际使用中考虑适当的退出条件或限制重试次数。
|
||||
return data['city'].rstrip('市')
|
||||
logging.error("定位失败: %s", data.get('message'))
|
||||
except Exception as e:
|
||||
logging.error("定位异常: %s", str(e))
|
||||
time.sleep(180)
|
||||
|
||||
def schedule_getWeath():
|
||||
"""调度 getWeath 函数每3分钟执行一次"""
|
||||
getWeath()
|
||||
Timer(180, schedule_getWeath).start() # 重新设置定时器
|
||||
"""定时任务调度"""
|
||||
try:
|
||||
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 = {
|
||||
'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/'
|
||||
}
|
||||
current_city = get_current_city()
|
||||
if current_city:
|
||||
area_id = get_area_id(current_city)
|
||||
if area_id:
|
||||
city = area_id
|
||||
|
||||
try:
|
||||
response = requests.get('https://d1.weather.com.cn/sk_2d/'+city+'.html',headers=headers)
|
||||
response.raise_for_status() # 检查请求是否成功
|
||||
response.encoding = 'utf-8'
|
||||
Weath = response.text[11:]
|
||||
fileHandle = open('/root/2.13-Ink-screen-clock/bin/weather.json', 'w')
|
||||
fileHandle.write(str(Weath))
|
||||
fileHandle.close()
|
||||
print("天气文件更新")
|
||||
except requests.RequestException as e:
|
||||
logging.error("获取天气数据时出现网络错误: %s", e)
|
||||
resp = requests.get(
|
||||
f'https://d1.weather.com.cn/sk_2d/{area_id}.html',
|
||||
headers=headers,
|
||||
timeout=15
|
||||
)
|
||||
resp.encoding = 'utf-8' # 关键修改:强制设置响应编码
|
||||
resp.raise_for_status()
|
||||
|
||||
# 直接处理原始字节数据
|
||||
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:
|
||||
logging.error("发生了意外错误: %s", e)
|
||||
logging.error("天气更新失败: %s", str(e))
|
||||
|
||||
try:
|
||||
schedule_getWeath() # 开始调度天气获取函数
|
||||
except OSError as e:
|
||||
logging.info(e)
|
||||
except KeyboardInterrupt:
|
||||
logging.info("检测到键盘中断,正在退出")
|
||||
except Exception as e:
|
||||
logging.error("发生了意外错误: %s", e)
|
||||
exit()
|
||||
|
||||
# 脚本正常结束后的清理操作
|
||||
exit()
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
schedule_getWeath()
|
||||
while True:
|
||||
time.sleep(1) # 保持主线程存活
|
||||
except KeyboardInterrupt:
|
||||
logging.info("程序已终止")
|
||||
BIN
pic/Fonttt.ttf
Normal file
BIN
pic/Fonttt.ttf
Normal file
Binary file not shown.
BIN
pic/GB2312.ttf
Normal file
BIN
pic/GB2312.ttf
Normal file
Binary file not shown.
BIN
pic/SmileySans-Oblique.otf
Normal file
BIN
pic/SmileySans-Oblique.otf
Normal file
Binary file not shown.
BIN
pic/SmileySans-Oblique.otf.woff2
Normal file
BIN
pic/SmileySans-Oblique.otf.woff2
Normal file
Binary file not shown.
BIN
pic/SmileySans-Oblique.ttf
Normal file
BIN
pic/SmileySans-Oblique.ttf
Normal file
Binary file not shown.
BIN
pic/SmileySans-Oblique.ttf.woff2
Normal file
BIN
pic/SmileySans-Oblique.ttf.woff2
Normal file
Binary file not shown.
BIN
pic/印品鸿蒙体_超粗黑版(非商用)_©字体视界.ttf
Normal file
BIN
pic/印品鸿蒙体_超粗黑版(非商用)_©字体视界.ttf
Normal file
Binary file not shown.
BIN
pic/原神cn.ttf
Normal file
BIN
pic/原神cn.ttf
Normal file
Binary file not shown.
BIN
pic/星穹铁道cn.ttf
Normal file
BIN
pic/星穹铁道cn.ttf
Normal file
Binary file not shown.
Reference in New Issue
Block a user