37 Commits

Author SHA1 Message Date
星光-k
863e9b2f5d Add files via upload 2025-01-17 02:40:52 +00:00
星光-k
d523a31006 Add files via upload 2025-01-17 02:40:26 +00:00
星光-k
9d4895fca4 Add files via upload 2025-01-17 02:02:59 +00:00
星光-k
e7f71c699e Add files via upload 2025-01-17 02:02:07 +00:00
星光-k
419f44be7e Add files via upload 2025-01-17 02:01:40 +00:00
星光-k
6c90e54728 Update clean.py 2025-01-17 07:08:49 +08:00
星光-k
e70b05a529 Update main.py 2025-01-17 07:08:17 +08:00
星光-k
d8c12f7ad3 Update weather.py 2025-01-17 07:07:49 +08:00
星光-k
8eb21afb19 更新 weather.py 2025-01-16 20:15:21 +00:00
星光-k
7bc892d06b 更新 weather.py 2025-01-16 20:06:11 +00:00
星光-k
ca67499854 更新 weather.py 2025-01-16 19:17:51 +00:00
星光-k
0b5623d5f6 更新 main.py 2025-01-16 19:17:20 +00:00
星光-k
7a71514224 Add files via upload 2025-01-16 12:09:19 +00:00
星光-k
fac4c591fb 更新 install.sh 2025-01-16 11:55:34 +00:00
星光-k
95e6bb12be Add files via upload 2025-01-16 11:54:01 +00:00
星光-k
57ea23a6fa Update app.py 2025-01-16 19:53:20 +08:00
星光-k
5262d729fb Add files via upload 2025-01-16 11:52:16 +00:00
星光-k
428d056e58 Create index.html 2025-01-16 19:51:13 +08:00
星光-k
066d9676f3 Add files via upload 2025-01-16 11:50:31 +00:00
星光-k
54bb2ccf21 Create app.py 2025-01-16 19:50:01 +08:00
星光-k
47e6ae681a Update weather.py 2025-01-16 09:53:18 +08:00
星光-k
7e15bf4172 Update weather.py 2025-01-16 09:52:03 +08:00
星光-k
7eeb7ceb12 Update README.md 2025-01-16 09:43:40 +08:00
星光-k
6a498cc04f Update weather.py 2025-01-16 09:38:10 +08:00
星光-k
7e302d0843 Update clean.py 2025-01-16 09:30:43 +08:00
星光-k
04930156b6 Update main.py 2025-01-16 09:30:21 +08:00
星光-k
5543bc6710 Update weather.py 2025-01-16 09:27:11 +08:00
星光-k
0fe27553f4 Update README.md 2025-01-16 08:45:27 +08:00
星光-k
9fe9e9f71a Update README.md 2025-01-16 08:44:09 +08:00
星光-k
3752c55b17 Update README.md 2025-01-16 08:42:42 +08:00
星光-k
620f363916 Update README.md 2025-01-16 08:38:21 +08:00
星光-k
b184f08914 Update main.py 2025-01-16 08:29:51 +08:00
星光-k
8efc57e655 Update weather.py 2025-01-16 08:28:19 +08:00
星光-k
a4e39c00fe Update weather.py 2025-01-16 08:13:41 +08:00
星光-k
62dc79de18 Update main.py 2025-01-16 06:54:45 +08:00
星光-k
d58d806da5 Update start.sh 2025-01-16 03:36:09 +08:00
星光-k
693595ef0f Rename wenter.py to weather.py 2025-01-16 03:35:17 +08:00
13 changed files with 1567 additions and 73 deletions

View File

@@ -8,10 +8,10 @@
## API说明:
#### 一言API
此网站可以获取指定长度指定类型的一个句子,可以限定返回长度及返回类型
~~#### 一言API~~
~~此网站可以获取指定长度指定类型的一个句子,可以限定返回长度及返回类型~~
https://international.v1.hitokoto.cn/?c=a&encode=text&max_length=20
~~https://international.v1.hitokoto.cn/?c=a&encode=text&max_length=20~~
#### 天气API
获取的天气是通过网页的接口,获取的内容保存在当前目录下的json文件接口的地址是在这里抓取的
@@ -68,7 +68,7 @@ sudo reboot
--gitcn 克隆中国仓库
--pisugar-wifi-conf 安装pisugar-wifi-conf
--pisugar-power-manager 安装pisugar-power-manager
--version <tag> 版本号
--version <tag> 版本号(使用方法 --version + 仓库标签,格式例如 v1.x.x ,可以是主仓库main)
--debug 输出详细信息
```
###
@@ -78,7 +78,7 @@ curl -sSL https://gitee.com/xingguangk/2.13-Ink-screen-clock/raw/main/bin/instal
```
```Bash
#中国源全参数设置(不使用--debug参数)
curl -sSL https://gitee.com/xingguangk/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash -s -- --version <tag> --zh --cn --gitcn --pisugar-power-manager --pisugar-wifi-conf
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>
```
```Bash
#默认源默认设置
@@ -86,7 +86,7 @@ curl -sSL https://github.com/kxgx/2.13-Ink-screen-clock/raw/main/bin/install.sh
```
```Bash
#默认源全参数设置(不使用--debug参数)
curl -sSL https://github.com/kxgx/2.13-Ink-screen-clock/raw/main/bin/install.sh | sudo bash -s -- --version <tag> --zh --cn --gitcn --pisugar-power-manager --pisugar-wifi-conf
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>
```
## 需要安装的软件和依赖:
@@ -113,7 +113,7 @@ sudo apt-get update && sudo apt-get install -y git pigpio i2c-tools netcat* gawk
# 如果使用的是非lite系统请在pip3安装部分添加
--break-system-packages
```
代码文件第三十三行,此次代码需要更改,否则将展示默认城市天气数据
weanther.py文件第64行可以修改默认城市数据
# 效果展示
总体采用局刷方案,程序运行后一直处于程序的获取新数据的过程中,当发现数据变化后即开始自动局刷。
![image](https://github.com/kxgx/2.13-Ink-screen-clock/raw/main/pic/1736749257603.jpg)

79
app/app.py Normal file
View File

@@ -0,0 +1,79 @@
from flask import Flask, render_template, request, send_from_directory, redirect, url_for, jsonify
import os
import re
import subprocess
app = Flask(__name__, template_folder='webui', static_url_path='', static_folder='webui')
FONT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'pic') # 字体文件夹路径
MAIN_PY_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'bin', 'main.py')
def list_font_files(font_dir):
try:
return os.listdir(font_dir)
except Exception as e:
print(f"Error listing font files: {e}")
return [] # 返回空列表以避免迭代错误
@app.route('/execute-shell')
def execute_shell():
# 替换以下命令为您想要执行的Shell命令
command = "sudo reboot now"
result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
return jsonify({'status': 'success', 'output': result.stdout})
else:
return jsonify({'status': 'error', 'output': result.stderr})
@app.route('/edit_main_py')
def edit_main_py():
try:
with open(MAIN_PY_PATH, 'r') as file:
content = file.read()
except Exception as e:
return f"Error reading main.py: {e}", 500
return render_template('edit_main_py.html', content=content)
@app.route('/save_main_py', methods=['POST'])
def save_main_py():
new_content = request.form.get('content')
if new_content is None:
return "No content provided", 400
try:
with open(MAIN_PY_PATH, 'w') as file:
file.write(new_content)
except Exception as e:
return f"Error saving main.py: {e}", 500
return redirect(url_for('index'))
@app.route('/')
def index():
font_files = list_font_files(FONT_DIR)
return render_template('index.html', font_files=font_files)
@app.route('/upload', methods=['POST'])
def upload():
if 'font_file' not in request.files:
return '没有文件部分'
file = request.files['font_file']
if file.filename == '':
return '没有选择文件'
if file:
filename = os.path.join(FONT_DIR, file.filename)
file.save(filename)
return '文件已上传成功'
@app.route('/update_font_names')
def update_font_names():
font_files = list_font_files(FONT_DIR)
return render_template('update_font_names.html', font_files=font_files)
@app.route('/fonts/<filename>')
def fonts(filename):
return send_from_directory(FONT_DIR, filename)
if not os.path.exists(FONT_DIR):
os.makedirs(FONT_DIR)
if __name__ == '__main__':
# 绑定到0.0.0.0,允许远程访问
app.run(host='0.0.0.0', port=80, debug=False)

9
app/webui/default.min.css vendored Normal file
View File

@@ -0,0 +1,9 @@
/*!
Theme: Default
Description: Original highlight.js style
Author: (c) Ivan Sagalaev <maniac@softwaremaniacs.org>
Maintainer: @highlightjs/core-team
Website: https://highlightjs.org/
License: see project LICENSE
Touched: 2021
*/pre code.hljs{display:block;overflow-x:auto;padding:1em}code.hljs{padding:3px 5px}.hljs{background:#f3f3f3;color:#444}.hljs-comment{color:#697070}.hljs-punctuation,.hljs-tag{color:#444a}.hljs-tag .hljs-attr,.hljs-tag .hljs-name{color:#444}.hljs-attribute,.hljs-doctag,.hljs-keyword,.hljs-meta .hljs-keyword,.hljs-name,.hljs-selector-tag{font-weight:700}.hljs-deletion,.hljs-number,.hljs-quote,.hljs-selector-class,.hljs-selector-id,.hljs-string,.hljs-template-tag,.hljs-type{color:#800}.hljs-section,.hljs-title{color:#800;font-weight:700}.hljs-link,.hljs-operator,.hljs-regexp,.hljs-selector-attr,.hljs-selector-pseudo,.hljs-symbol,.hljs-template-variable,.hljs-variable{color:#ab5656}.hljs-literal{color:#695}.hljs-addition,.hljs-built_in,.hljs-bullet,.hljs-code{color:#397300}.hljs-meta{color:#1f7199}.hljs-meta .hljs-string{color:#38a}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:700}

View File

@@ -0,0 +1,59 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>编辑 main.py</title>
<!-- 引用本地的highlight.js CSS -->
<link rel="stylesheet" href="{{ url_for('static', filename='default.min.css') }}">
</head>
<body>
<h1>编辑 main.py</h1>
<!-- 添加一个表单来提交编辑后的代码 -->
<form method="post" action="{{ url_for('save_main_py') }}">
<pre style="background-color: black !important;"><code class="python" id="code">{{ content }}</code></pre>
<input type="hidden" name="content" id="hidden-content">
<input type="submit" value="保存">
</form>
<!-- 引用本地的highlight.js JavaScript -->
<script src="{{ url_for('static', filename='highlight.min.js') }}"></script>
<script>
// 初始化highlight.js
document.addEventListener('DOMContentLoaded', (event) => {
hljs.highlightAll();
});
</script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var preElements = document.querySelectorAll('pre.code-editor');
preElements.forEach(function(pre) {
pre.style.backgroundColor = 'black';
});
});
</script>
<h2>重启</h2>
</head>
<body>
<button id="executeShellBtn">重启</button>
<script>
document.getElementById('executeShellBtn').addEventListener('click', function() {
fetch('/execute-shell')
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
alert('Command executed successfully:\n' + data.output);
} else {
alert('Error executing command:\n' + data.output);
}
})
.catch(error => {
alert('Error: ' + error);
});
});
</script>
</body>
</html>
 

1213
app/webui/highlight.min.js vendored Normal file

File diff suppressed because one or more lines are too long

27
app/webui/index.html Normal file
View File

@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>字体上传和管理</title>
</head>
<body>
<h1>上传字体文件</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="font_file">
<input type="submit" value="上传">
</form>
<h2>已上传的字体文件:</h2>
<ul>
{% for font_file in font_files %}
<li>{{ font_file }}</li>
{% else %}
<li>没有找到字体文件。</li>
{% endfor %}
</ul>
<!-- 添加跳转到edit_main_py的按钮 -->
<a href="/edit_main_py"><button>编辑main.py</button></a>
</body>
</html>

View File

@@ -0,0 +1,26 @@
<!-- update_font_names.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>更新字体文件名</title>
</head>
<body>
<h1>更新字体文件名</h1>
<form method="post" action="/save_font_names">
<label for="font01">字体文件名 01:</label>
<input type="text" id="font01" name="font01"><br>
<label for="font02">字体文件名 02:</label>
<input type="text" id="font02" name="font02"><br>
<label for="font03">字体文件名 03:</label>
<input type="text" id="font03" name="font03"><br>
<label for="font04">字体文件名 04:</label>
<input type="text" id="font04" name="font04"><br>
<label for="font05">字体文件名 05:</label>
<input type="text" id="font05" name="font05"><br>
<label for="font06">字体文件名 06:</label>
<input type="text" id="font06" name="font06"><br>
<input type="submit" value="保存">
</form>
</body>
</html>

View File

@@ -16,39 +16,39 @@ if os.path.exists(libdir):
from waveshare_epd import epd2in13_V4 #引入墨水屏驱动文件
# 配置日志
logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def clear_screen():
try:
logging.info("Starting e-Paper clear screen script")
logging.info("启动电子纸清屏脚本")
# 初始化并创建一个 epd2in13_V4 对象
epd = epd2in13_V4.EPD()
# 初始化屏幕
logging.info("Initializing e-Paper display")
logging.info("初始化电子纸显示屏")
epd.init()
# 清除屏幕
logging.info("Clearing e-Paper display")
logging.info("清除电子纸显示屏内容")
epd.Clear(0xFF)
# 等待一段时间,确保清除操作完成
#time.sleep(1)
# 将屏幕置于睡眠模式
logging.info("Putting e-Paper display to sleep")
logging.info("将电子纸显示屏置入睡眠状态")
epd.sleep()
epd2in13_V4.epdconfig.module_exit(cleanup=True)
exit()
logging.info("e-Paper display cleared successfully")
logging.info("电子纸显示屏清屏成功")
except IOError as e:
logging.info(e)
except KeyboardInterrupt:
logging.info("Ctrl+C pressed, exiting")
logging.info("检测到键盘中断,正在退出")
epd2in13_V4.epdconfig.module_exit(cleanup=True)
exit()

View File

@@ -215,7 +215,7 @@ install_packages() {
# 安装pip包函数
install_pip_packages() {
echo "正在安装pip软件包"
if ! sudo pip3 install -i "$PIPY_MIRROR" spidev borax pillow requests; then
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

View File

@@ -8,9 +8,11 @@ import subprocess
import os
from threading import Timer
import requests
import socket
white = 255 #颜色
black = 0
logging.basicConfig(level=logging.INFO)
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')
@@ -40,6 +42,17 @@ 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()
# 检查是否为IPv4地址
if ip_output and not ip_output.startswith("127."):
return ip_output
else:
return "IPv4获取失败"
except subprocess.CalledProcessError as e:
return f"获取失败"
def CPU_temperature():#CPU温度获取
temperatura = os.popen('vcgencmd measure_temp').readline()
temperatura = temperatura.replace('temp=','').strip()
@@ -64,16 +77,16 @@ def Bottom_edge(): #在图片中添加底边内容
draw.line((157,113,157,115),fill=255, width=1)
global power_str
power_str=power_battery()
draw.text((128,108),power_str,font = font04,fill =255) #显示当前电量百分比
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_address() #获取当前IP地址
local_addr= Get_ipv4_address() #获取当前IP地址
draw.text((10,107),"IP:"+local_addr,font = font05,fill =255)#显示当前IP地址
def Weather(): #在图片中添加天气内容
Weather_json = open('weather.json','r')
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)
@@ -94,13 +107,15 @@ def Weather(): #在图片中添加天气内容
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("Refresh and prepare the basic content before starting the canvas")#开始画布前刷新准备基础内容
logging.info("在启动画布之前,刷新并准备基本内容")#开始画布前刷新准备基础内容
global get_date_var
get_date_var=get_date() #记录开始数据
draw.text((2,2),get_date_var,font = font02,fill =0)#将日期及星期几显示到屏幕
@@ -115,7 +130,7 @@ def Partial_full_brush(): #局部定时全刷函数
logging.debug("局部定时全局刷新")
epd.init()
def Partial_refresh():#局刷函数
logging.info("Partial content update, this update is recommended to be synchronized with the minute to save the life of the ink screen")#局部内容更新,此更新建议与分钟同步,以节省墨水屏寿命
logging.info("部分内容更新,此更新建议与分钟同步,以节省墨水屏的使用寿命")#局部内容更新,此更新建议与分钟同步,以节省墨水屏寿命
epd.displayPartBaseImage(epd.getbuffer(info_image.rotate(180)))
epd.init()
while (True):
@@ -135,14 +150,14 @@ 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.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('weather.json','r')
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)
@@ -178,6 +193,12 @@ def Partial_refresh():#局刷函数
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) #显示天气更新时间
@@ -189,7 +210,7 @@ def Partial_refresh():#局刷函数
power_str1 =power_battery()
if (power_str1==power_str) ==False:
draw.rectangle((128, 110, 153, 117), fill = 0) #设置更新时间刷新区域
draw.text((127,108),power_battery(),font = font04,fill =255) #显示当前电量百分比
draw.text((129,108),power_battery(),font = font04,fill =255) #显示当前电量百分比
power_str=power_str1
Local_strong_brush() #局部强刷
logging.info("电源电量局部刷新")
@@ -200,7 +221,7 @@ try:
#epd.Clear(0xFF) #清除屏幕内容
##################屏幕初始化#########################
logging.info("Width = %s, Height = %s", format(epd.width), format(epd.height)) #打印屏幕高度及宽度
logging.info("Initialize and clear the display")#屏幕开始准备相关展示
logging.info("初始化并清空显示屏")#屏幕开始准备相关展示
info_image = Image.new('1', (epd.height, epd.width), 255) #画布创建准备
draw = ImageDraw.Draw(info_image)
Basic_refresh() #全局刷新
@@ -208,10 +229,10 @@ try:
epd.init()
epd.Clear(0xFF)
epd.sleep()
except IOError as e:
except OSError as e:
logging.info(e)
except KeyboardInterrupt:
logging.info("Keyboard interrupt detected, exiting gracefully.")
logging.info("检测到键盘中断,正在清理并退出")
epd.init()
epd.Clear(0xFF) # 清除屏幕内容
epd.sleep() # 使屏幕进入休眠状态
@@ -219,7 +240,7 @@ except KeyboardInterrupt:
exit()
except Exception as e:
logging.error("An unexpected error occurred: %s", e)
logging.error("发生了意外的错误: %s", e)
epd.init()
epd.Clear(0xFF) # 清除屏幕内容
epd.sleep() # 使屏幕进入休眠状态

View File

@@ -1,8 +1,10 @@
#!/bin/bash
f_name=main.py
f1_name=wenter.py
f1_name=weather.py
f2_name=app.py
dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
logdir="${dir%/*}/log"
appdir="${dir%/*}/app"
# 确保日志目录存在
mkdir -p "${logdir}"
pid=`ps -ef |grep $dir/$f_name | grep -v grep |awk '{print $2}'`
@@ -11,4 +13,5 @@ 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-wenter.log 2>&1 &
nohup /usr/bin/python3 -u $appdir/$f2_name > $logdir/info-app.log 2>&1 &

99
bin/weather.py Normal file
View File

@@ -0,0 +1,99 @@
#!/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 requests
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) # 将引入文件添加到环境变量
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(5) # 重试前等待5秒
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()
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(5) # 重试前等待5秒
# 注意:无限重试可能会在特定情况下导致程序无法终止,请确保在实际使用中考虑适当的退出条件或限制重试次数。
def getWeath(city='101060101'):
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',
'Referer': 'http://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('http://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()
Timer(180, getWeath).start() # 定时器函数,间隔三分钟下载文件至本地
print("天气文件更新")
except requests.RequestException as e:
logging.error("获取天气数据时出现网络错误: %s", e)
except Exception as e:
logging.error("发生了意外错误: %s", e)
try:
getWeath() # 天气获取函数开始运行
except IOError as e:
logging.info(e)
except KeyboardInterrupt:
logging.info("检测到键盘中断,正在退出")
except Exception as e:
logging.error("发生了意外错误: %s", e)
exit()
# 脚本正常结束后的清理操作
exit()

View File

@@ -1,42 +0,0 @@
#!/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 requests
white = 255 #颜色
black = 0
logging.basicConfig(level=logging.INFO)
################################引入配置文件开始################################################
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)#将引入文件添加到环境变量
def getWeath(city='101060111'): #天气函数,下载json天气至本地
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',
'Referer':'http://www.weather.com.cn/'
}
response = requests.get('http://d1.weather.com.cn/sk_2d/'+city+'.html',headers=headers)
response.encoding = 'utf-8'
Weath=response.text[11:]
fileHandle=open('weather.json','w')
fileHandle.write(str(Weath))
fileHandle.close()
Timer(180, getWeath).start() #定时器函数,间隔三分钟下载文件至本地
print("天气文件更新")
try:
getWeath()#天气获取函数开始运行
except IOError as e:
logging.info(e)
except KeyboardInterrupt:
logging.info("Keyboard interrupt detected, exiting gracefully.")
except Exception as e:
logging.error("An unexpected error occurred: %s", e)
exit()
# 脚本正常结束后的清理操作
exit()