13 Commits

26 changed files with 3760 additions and 63 deletions

Binary file not shown.

135
1.1/frps.py Normal file
View File

@ -0,0 +1,135 @@
import requests
import json
import os
from datetime import datetime
# --- 配置保持不变 ---
BASE_URL = "http://106.75.72.40:7500/api/proxy/tcp"
PRIMARY_AUTH = "Basic YWRtaW46bGljYWhr"
X_AUTH = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJsb2NhbGUiOiJ6aC1jbiIsInZpZXdNb2RlIjoibGlzdCIsInNpbmdsZUNsaWNrIjpmYWxzZSwicGVybSI6eyJhZG1pbiI6dHJ1ZSwiZXhlY3V0ZSI6dHJ1ZSwiY3JlYXRlIjp0cnVlLCJyZW5hbWUiOnRydWUsIm1vZGlmeSI6dHJ1ZSwiZGVsZXRlIjp0cnVlLCJzaGFyZSI6dHJ1ZSwiZG93bmxvYWQiOnRydWV9LCJjb21tYW5kcyI6W10sImxvY2tQYXNzd29yZCI6ZmFsc2UsImhpZGVEb3RmaWxlcyI6ZmFsc2V9LCJleHAiOjE3Njc2Njg3NzgsImlhdCI6MTc2NzY2MTU3OCwiaXNzIjoiRmlsZSBCcm93c2VyIn0.z9zycFSf3XpUDRhGjziUJ-PUeHIsRba23AI6itqXM-w"
headers = {
"Authorization": PRIMARY_AUTH,
"x-auth": X_AUTH,
"User-Agent": "Mozilla/5.0"
}
def get_today_str():
return datetime.now().strftime("%Y_%m_%d")
def find_closest_item(items, is_date_level=True):
if not items or not isinstance(items, list): return None
today = datetime.now()
scored_items = []
for item in items:
if not isinstance(item, dict): continue
path = item.get('path', '')
if not path: continue
try:
if is_date_level:
date_str = path.split('/')[-1]
current_date = datetime.strptime(date_str, "%Y_%m_%d")
else:
mod_str = item.get('modified', '')
if mod_str:
current_date = datetime.fromisoformat(mod_str.replace('Z', '+00:00'))
else:
continue
diff = abs((today - current_date.replace(tzinfo=None)).total_seconds())
scored_items.append((diff, item))
except:
continue
if not scored_items: return None
scored_items.sort(key=lambda x: x[0])
return scored_items[0][1]
def debug_process_106():
today_str = get_today_str()
print(f"=== 开始 106 网站深度调试 (目标日期: {today_str}) ===")
try:
resp = requests.get(BASE_URL, headers=headers, timeout=15)
if resp.status_code != 200:
print(f"❌ 错误: 主接口访问失败, 状态码: {resp.status_code}")
return
proxies = resp.json().get('proxies', [])
data_proxies = [p for p in proxies if p.get('name', '').endswith('_data')]
for item in data_proxies:
name = item.get('name', 'Unknown')
# 每一个站点的处理都包裹在独立的 try 里,防止相互干扰
try:
status = str(item.get('status', '')).lower().strip()
conf = item.get('conf') or {}
port = conf.get('remote_port')
print(f"--- [检查站点: {name}] ---")
if status != 'online':
print(f" ⚠ 判定错误: 站点离线 ({status})")
continue
if not port:
print(f" ❌ 判定错误: 缺少端口配置")
continue
# Data 目录请求
res2 = requests.get(f"http://106.75.72.40:{port}/api/resources/Data/", headers=headers, timeout=10)
if res2.status_code != 200:
print(f" ❌ 判定错误: Data目录 HTTP {res2.status_code}")
continue
it2 = res2.json().get('items', [])
closest_date = find_closest_item(it2, True)
if not closest_date:
print(f" ❌ 判定错误: Data目录为空")
continue
path_date = closest_date.get('path', '')
date_val = path_date.split('/')[-1]
if date_val != today_str:
print(f" ⚠ 判定错误: 日期不符 (最新: {date_val})")
continue
# 文件列表请求
res3 = requests.get(f"http://106.75.72.40:{port}/api/resources{path_date}/", headers=headers,
timeout=10)
it3 = res3.json().get('items', [])
closest_file = find_closest_item(it3, False)
if not closest_file:
print(f" ❌ 判定错误: 日期文件夹内无文件")
continue
# 文件内容请求 - 关键防御点
path_csv = closest_file.get('path', '')
res4 = requests.get(f"http://106.75.72.40:{port}/api/resources{path_csv}", headers=headers, timeout=10)
try:
file_data = res4.json()
if file_data is None:
print(f" ❌ 判定错误: 接口返回了 Null (NoneType)")
continue
content = file_data.get('content', '')
if not content:
print(f" ❌ 判定错误: content 字段为空")
else:
print(f" ✅ 检查通过: 数据最新,长度 {len(content)}")
except Exception as json_e:
print(f" ❌ 判定错误: 解析 JSON 失败 (非标准格式)")
except Exception as site_e:
print(f" ❌ 判定错误: 站点逻辑崩溃: {site_e}")
except Exception as global_e:
print(f"❌ 全局严重错误: {global_e}")
if __name__ == "__main__":
debug_process_106()

169
1.1/frps_final.py Normal file
View File

@ -0,0 +1,169 @@
import requests
import json
import os
from datetime import datetime
# --- 基础配置 ---
BASE_URL = "http://106.75.72.40:7500/api/proxy/tcp"
PRIMARY_AUTH = "Basic YWRtaW46bGljYWhr"
LOGIN_PAYLOAD = {"username": "admin", "password": "licahk", "recaptcha": ""}
SAVE_DIR = "downloaded_data"
if not os.path.exists(SAVE_DIR):
os.makedirs(SAVE_DIR)
def get_today_str():
return datetime.now().strftime("%Y_%m_%d")
def get_dynamic_token(port):
"""
为指定端口的站点执行登录,获取最新的 x-auth token
"""
login_url = f"http://106.75.72.40:{port}/api/login"
try:
# 登录不需要 x-auth只需要 Basic Auth 或特定的 Payload
resp = requests.post(login_url, json=LOGIN_PAYLOAD, timeout=10)
if resp.status_code == 200:
# 登录成功后token 通常直接返回在响应体中(纯字符串或 JSON
token = resp.text.strip().replace('"', '')
return token
else:
print(f" ❌ 登录失败: 端口 {port}, 状态码 {resp.status_code}")
return None
except Exception as e:
print(f" ❌ 登录异常: {port}, {e}")
return None
def find_closest_item(items, is_date_level=True):
if not items or not isinstance(items, list): return None
today = datetime.now()
scored_items = []
today_str = get_today_str()
for item in items:
name_val = item.get('name', '')
path_val = item.get('path', '')
target_str = name_val if name_val else path_val.split('/')[-1]
try:
if is_date_level:
current_date = datetime.strptime(target_str, "%Y_%m_%d")
else:
mod_str = item.get('modified', '')
current_date = datetime.fromisoformat(mod_str.replace('Z', '+00:00'))
diff = abs((today - current_date.replace(tzinfo=None)).total_seconds())
scored_items.append((diff, item, target_str))
except:
continue
if not scored_items: return None
scored_items.sort(key=lambda x: x[0])
return scored_items[0]
def process_site(proxy_item):
name = proxy_item.get('name', '')
# 严格过滤:只处理以 _data 结尾的站点
if not name.lower().endswith('_data'):
return
name_upper = name.upper()
is_tower_underscore = "TOWER_" in name_upper
is_tower_i = "TOWER" in name_upper and not is_tower_underscore
if not (is_tower_underscore or is_tower_i):
return
print(f"\n--- [正在处理站点: {name}] ---")
try:
port = proxy_item.get('conf', {}).get('remote_port')
if not port: return
# 动态获取当前站点的 Token
token = get_dynamic_token(port)
if not token:
print(f" 跳过: 无法获取有效的 x-auth")
return
headers = {
"Authorization": PRIMARY_AUTH,
"x-auth": token,
"User-Agent": "Mozilla/5.0"
}
today_str = get_today_str()
# Step 1: 进入 data 根目录 (路径根据类型区分大小写)
api_root = "/api/resources/Data/" if is_tower_underscore else "/api/resources/data/"
res1 = requests.get(f"http://106.75.72.40:{port}{api_root}", headers=headers, timeout=10)
# Step 2: 寻找并进入日期目录
items1 = res1.json().get('items', [])
best_date = find_closest_item(items1, is_date_level=True)
if not best_date or best_date[2] != today_str:
print(f" ⚠ 跳过: 未找到今日 ({today_str}) 的文件夹")
return
date_path = f"{api_root}{best_date[2]}/"
res2 = requests.get(f"http://106.75.72.40:{port}{date_path}", headers=headers, timeout=10)
# Step 3: 寻找日期目录下的最新文件
items2 = res2.json().get('items', [])
best_file = find_closest_item(items2, is_date_level=False)
if not best_file:
print(f" ❌ 日期文件夹内无文件")
return
# 获取文件的完整 path
file_item = best_file[1]
full_path = file_item.get('path')
if not full_path:
full_path = f"{date_path}{file_item.get('name')}"
# --- 获取内容层级 (根据站点类型采用不同接口) ---
if is_tower_i:
# TowerI 模式:使用 /api/raw/{path} 获取二进制流
download_url = f"http://106.75.72.40:{port}/api/raw{full_path}"
res3 = requests.get(download_url, headers=headers, timeout=20, stream=True)
if res3.status_code == 200:
save_path = os.path.join(SAVE_DIR, f"{name}_{today_str}.bin")
with open(save_path, 'wb') as f:
f.write(res3.content)
print(f" ✅ 二进制保存成功: {save_path} (大小: {len(res3.content)} 字节)")
else:
# Tower_ 模式:原来的 JSON content 模式
file_api_url = f"http://106.75.72.40:{port}/api/resources{full_path}"
res3 = requests.get(file_api_url, headers=headers, timeout=20)
try:
content_str = res3.json().get('content', '')
if content_str:
save_path = os.path.join(SAVE_DIR, f"{name}_{today_str}.json")
with open(save_path, 'w', encoding='utf-8') as f:
f.write(content_str)
print(f" ✅ JSON数据保存成功: {save_path}")
except:
print(f" ❌ TOWER_ 站点格式错误或无内容")
except Exception as e:
print(f" ❌ 站点处理失败: {str(e)}")
def main():
print(f"任务启动: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
# 主接口获取站点列表
try:
# 注意:主控制台可能也需要 token这里先用硬编码如果不行也需要为 7500 端口做登录
main_headers = {"Authorization": PRIMARY_AUTH, "User-Agent": "Mozilla/5.0"}
resp = requests.get(BASE_URL, headers=main_headers, timeout=15)
proxies = resp.json().get('proxies', [])
for p in proxies:
process_site(p)
except Exception as e:
print(f"❌ 全局错误: {e}")
if __name__ == "__main__":
main()

327
1.1/test1.py Normal file
View File

@ -0,0 +1,327 @@
import os
import sys
import json
import threading
import requests
import logging
from datetime import datetime
from flask import Flask, jsonify, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from flask_apscheduler import APScheduler
from lxml import etree
# --- 配置日志 ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# --- 关键路径处理函数 (适配 PyInstaller) ---
def get_base_path():
"""获取运行时及其所在目录适配开发环境和打包后的EXE环境"""
if getattr(sys, 'frozen', False):
# 如果是打包后的 exesys.executable 是 exe 的路径
return os.path.dirname(sys.executable)
# 开发环境下,是当前脚本的路径
return os.path.dirname(os.path.abspath(__file__))
def get_static_path():
"""获取 Vue 静态资源 dist 的路径"""
if getattr(sys, 'frozen', False):
# PyInstaller 打包时,资源文件会被解压到 sys._MEIPASS 临时目录
# 我们需要在打包命令中指定 --add-data "dist;dist"
return os.path.join(sys._MEIPASS, 'dist')
# 开发环境
return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'dist')
# --- Flask 初始化 ---
# static_folder 指向 Vue 打包后的 dist 目录
# static_url_path='' 表示静态文件不需要 /static 前缀
dist_folder = get_static_path()
app = Flask(__name__, static_folder=dist_folder, static_url_path='')
CORS(app)
# --- 数据库配置 ---
# 确保数据库生成在 exe 同级目录下,而不是临时文件夹中
db_path = os.path.join(get_base_path(), 'monitor_data.db')
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SCHEDULER_API_ENABLED'] = True
db = SQLAlchemy(app)
scheduler = APScheduler()
# --- 模型定义 (保持不变) ---
class MonitorRecord(db.Model):
id = db.Column(db.Integer, primary_key=True)
source = db.Column(db.String(50))
name = db.Column(db.String(100))
status = db.Column(db.String(50))
reason = db.Column(db.String(255))
offset = db.Column(db.String(50))
latest_time = db.Column(db.String(50))
check_time = db.Column(db.String(50))
content = db.Column(db.Text, nullable=True)
with app.app_context():
db.create_all()
# --- 爬虫配置 (保持不变) ---
CONFIG = {
"106": {
"base_url": "http://106.75.72.40:7500/api/proxy/tcp",
"primary_auth": "Basic YWRtaW46bGljYWhr",
"login_payload": {"username": "admin", "password": "licahk", "recaptcha": ""}
},
"82": {
"base_url": "http://82.156.1.111/weather/php",
"login": {'username': 'renlixin', 'password': 'licahk', 'login': '123'}
}
}
is_running = False
# --- 核心辅助函数 (保持不变) ---
def calculate_offset(latest_time_str):
if not latest_time_str or latest_time_str == "N/A":
return "从未同步"
try:
clean_date_str = str(latest_time_str).split()[0].replace('_', '-')
target_date = datetime.strptime(clean_date_str, "%Y-%m-%d").date()
diff = (datetime.now().date() - target_date).days
if diff == 0: return "当天已同步"
return f"滞后 {diff}"
except:
return "时间解析失败"
def save_record(source, name, status, reason, latest_time="N/A", content=None):
record = MonitorRecord.query.filter_by(source=source, name=name).first()
now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
current_offset = calculate_offset(latest_time)
if record:
if content is not None: record.content = content
if latest_time != "N/A": record.latest_time = latest_time
record.status = status
record.reason = reason
record.check_time = now_str
time_base = latest_time if latest_time != "N/A" else record.latest_time
record.offset = calculate_offset(time_base)
else:
new_record = MonitorRecord(
source=source, name=name, status=status, reason=reason,
offset=current_offset, latest_time=latest_time,
check_time=now_str, content=content
)
db.session.add(new_record)
try:
db.session.commit()
except Exception as e:
db.session.rollback()
logging.error(f"DB Error: {e}")
return f"{source}_{name}"
# --- 业务逻辑函数 (保持不变) ---
def get_106_dynamic_token(port):
try:
login_url = f"http://106.75.72.40:{port}/api/login"
resp = requests.post(login_url, json=CONFIG["106"]["login_payload"], timeout=10)
return resp.text.strip().replace('"', '') if resp.status_code == 200 else None
except:
return None
def find_closest_item(items, is_date_level=True):
if not items or not isinstance(items, list): return None
today = datetime.now()
scored_items = []
for item in items:
name_val = item.get('name', '')
path_val = item.get('path', '')
target_str = name_val if name_val else path_val.split('/')[-1]
try:
if is_date_level:
current_date = datetime.strptime(target_str, "%Y_%m_%d")
else:
mod_str = item.get('modified', '')
current_date = datetime.fromisoformat(mod_str.replace('Z', '+00:00'))
diff = abs((today - current_date.replace(tzinfo=None)).total_seconds())
scored_items.append((diff, item, target_str))
except:
continue
if not scored_items: return None
scored_items.sort(key=lambda x: x[0])
return scored_items[0]
def run_106_logic(active_set):
# (保持原样,省略以节省空间,直接用你原本的逻辑即可)
c = CONFIG["106"]
today_str = datetime.now().strftime("%Y_%m_%d")
main_headers = {"Authorization": c["primary_auth"], "User-Agent": "Mozilla/5.0"}
try:
resp = requests.get(c["base_url"], headers=main_headers, timeout=20)
proxies = resp.json().get('proxies', [])
for item in proxies:
name = item.get('name', '')
if not name.lower().endswith('_data'): continue
if "TOWER" not in name.upper(): continue
if str(item.get('status')).lower() != 'online':
key = save_record("106网站", name, "离线", f"设备状态: {item.get('status')}")
active_set.add(key)
continue
try:
port = item.get('conf', {}).get('remote_port')
token = get_106_dynamic_token(port)
if not token:
key = save_record("106网站", name, "异常", "Token获取失败")
active_set.add(key)
continue
headers = {"Authorization": c["primary_auth"], "x-auth": token}
api_root = "/api/resources/Data/" if "TOWER_" in name.upper() else "/api/resources/data/"
res1 = requests.get(f"http://106.75.72.40:{port}{api_root}", headers=headers, timeout=10)
best_date = find_closest_item(res1.json().get('items', []), True)
if not best_date or best_date[2] != today_str:
key = save_record("106网站", name, "正常", "未找到今日文件夹",
latest_time=best_date[2] if best_date else "N/A")
active_set.add(key)
continue
date_path = f"{api_root}{best_date[2]}/"
res2 = requests.get(f"http://106.75.72.40:{port}{date_path}", headers=headers, timeout=10)
best_file = find_closest_item(res2.json().get('items', []), False)
if not best_file:
key = save_record("106网站", name, "正常", "今日文件夹为空", latest_time=today_str)
active_set.add(key)
continue
file_item = best_file[1]
full_path = file_item.get('path') or f"{date_path}{file_item.get('name')}"
is_tower_i = "TOWER" in name.upper() and "TOWER_" not in name.upper()
if is_tower_i:
download_url = f"http://106.75.72.40:{port}/api/raw{full_path}"
res3 = requests.get(download_url, headers=headers, timeout=20)
final_content = f"Binary Data Size: {len(res3.content)}"
else:
file_api_url = f"http://106.75.72.40:{port}/api/resources{full_path}"
res3 = requests.get(file_api_url, headers=headers, timeout=20)
final_content = res3.json().get('content', '')
key = save_record("106网站", name, "正常", "同步成功", latest_time=today_str, content=final_content)
active_set.add(key)
except Exception as e:
key = save_record("106网站", name, "异常", f"采集错误: {str(e)[:50]}")
active_set.add(key)
except Exception as e:
logging.error(f"106 Global Error: {e}")
def run_82_logic(active_set):
# (保持原样,直接用你原本的逻辑即可)
c = CONFIG["82"]
session = requests.Session()
try:
session.post(f"{c['base_url']}/login.php", data=c["login"], timeout=10)
resp = session.post(f"{c['base_url']}/GetStationList.php", timeout=10)
stations = etree.HTML(resp.content).xpath('//option/@value')
for sid in [s for s in stations if s]:
try:
r = session.post(f"{c['base_url']}/getLastWeatherData.php", data=str(sid),
headers={'Content-Type': 'text/plain'}, timeout=10)
data = r.json()
if data:
d_list = data.get('date', [])
latest = str(d_list[-1]) if d_list else "N/A"
key = save_record("82网站", sid, "正常", "同步成功", latest_time=latest,
content=json.dumps(data, ensure_ascii=False))
active_set.add(key)
else:
key = save_record("82网站", sid, "异常", "返回空数据")
active_set.add(key)
except:
key = save_record("82网站", sid, "异常", "单个采集失败")
active_set.add(key)
except Exception as e:
logging.error(f"82 Global Error: {e}")
def execute_monitor_task():
global is_running
if is_running: return
is_running = True
logging.info("Starting monitor task...")
with app.app_context():
active_set = set()
run_106_logic(active_set)
run_82_logic(active_set)
all_records = MonitorRecord.query.all()
now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for record in all_records:
if f"{record.source}_{record.name}" not in active_set:
record.status = "已离线"
record.reason = "设备本次未出现"
record.check_time = now_str
record.offset = calculate_offset(record.latest_time)
try:
db.session.commit()
except:
db.session.rollback()
is_running = False
logging.info("Monitor task finished.")
# --- API 路由 (保持不变) ---
@app.route('/api/run', methods=['POST'])
def manual_start():
if is_running: return jsonify({"status": "busy"}), 400
threading.Thread(target=execute_monitor_task).start()
return jsonify({"status": "started"})
@app.route('/api/status')
def status(): return jsonify({"is_running": is_running})
@app.route('/api/logs')
def logs():
data = MonitorRecord.query.all()
return jsonify([{
"source": l.source, "name": l.name, "status": l.status,
"reason": l.reason, "offset": l.offset, "latest_time": l.latest_time,
"check_time": l.check_time, "content": l.content
} for l in data])
# --- 新增: 前端页面托管路由 ---
@app.route('/')
def serve_index():
return send_from_directory(app.static_folder, 'index.html')
@app.route('/<path:path>')
def serve_static_files(path):
# 尝试在 dist 目录寻找文件 (css, js, icons)
file_path = os.path.join(app.static_folder, path)
if os.path.exists(file_path):
return send_from_directory(app.static_folder, path)
# 如果找不到文件例如刷新页面时的路由返回index.html让Vue Router处理
return send_from_directory(app.static_folder, 'index.html')
# --- 调度器与启动 ---
@scheduler.task('cron', id='daily_job', hour=10, minute=0)
def auto_run_task():
with app.app_context():
threading.Thread(target=execute_monitor_task).start()
if __name__ == "__main__":
scheduler.init_app(app)
scheduler.start()
# Host='0.0.0.0' 允许外部IP访问
# Port=5000 (确保 Windows 防火墙开放了此端口)
print("应用正在启动... 请确保 dist 文件夹与脚本/exe 同级或已被打包")
app.run(host='0.0.0.0', port=5000, debug=False, use_reloader=False)

121
1.1/光谱气象站final.py Normal file
View File

@ -0,0 +1,121 @@
import os
import json
import time
import requests
from lxml import etree
from datetime import datetime
# --- 配置区 ---
BASE_URL = "http://82.156.1.111/weather/php"
LOGIN_DATA = {'username': 'renlixin', 'password': 'licahk', 'login': '123'}
OUTPUT_DIR = "weather_data_test"
os.makedirs(OUTPUT_DIR, exist_ok=True)
session = requests.Session()
def fetch_stations():
resp = session.post(f"{BASE_URL}/GetStationList.php")
if resp.status_code != 200: return []
tree = etree.HTML(resp.content)
stations = [s for s in tree.xpath('//option/@value') if s and str(s).strip()]
return stations
def get_latest_data_item(station_id, data_list):
"""
核心改进:从列表中筛选出日期距离今天最近的一条数据
"""
if not data_list or not isinstance(data_list, list):
return None
today = datetime.now().date()
parsed_items = []
for item in data_list:
try:
# 兼容处理:如果是字符串列表,直接解析;如果是对象列表,取特定键
date_str = item.split()[0] if isinstance(item, str) else item.get('date', '').split()[0]
current_date = datetime.strptime(date_str, "%Y-%m-%d").date()
# 计算与今天的差异(天数绝对值)
diff = abs((today - current_date).days)
parsed_items.append({
'diff': diff,
'date_obj': current_date,
'original_data': item
})
except:
continue
if not parsed_items:
return None
# --- 逻辑更新按时间差异升序排序diff越小说明离今天越近 ---
parsed_items.sort(key=lambda x: x['diff'])
# 返回距离最近的那一条原始数据
return parsed_items[0]
def save_json(name, data):
path = os.path.join(OUTPUT_DIR, f"{name}.json")
with open(path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def main():
print("正在登录...")
session.post(f"{BASE_URL}/login.php", data=LOGIN_DATA)
stations = fetch_stations()
print(f"成功获取 {len(stations)} 个有效站点")
for i, sid in enumerate(stations, 1):
print(f"[{i}/{len(stations)}] 处理站点: {sid}")
try:
resp = session.post(f"{BASE_URL}/getLastWeatherData.php",
data=str(sid),
headers={'Content-Type': 'text/plain'})
if resp.status_code == 200:
full_data = resp.json()
# 假设 API 返回的 JSON 中 'date' 键对应的是数据列表
# 我们调用 get_latest_data_item 来锁定那唯一的一条最新数据
data_key = 'date' if 'date' in full_data else 'items' # 根据实际键名调整
target_list = full_data.get(data_key, [])
latest_result = get_latest_data_item(sid, target_list)
if latest_result:
# 重新构造保存内容:只保留最接近今天的数据
final_payload = {
"proxy_name": sid,
"status": "online",
"latest_date": str(latest_result['date_obj']),
"days_diff": latest_result['diff'],
"data_content": latest_result['original_data']
}
# 如果不是今天,输出警告
if latest_result['diff'] != 0:
print(f" ⚠️ 非当天数据: {latest_result['date_obj']} (差 {latest_result['diff']} 天)")
else:
print(f" ✨ 数据已同步至今天")
save_json(sid, final_payload)
else:
print(f" ⚪ 站点 {sid} 未找到有效日期数据")
else:
print(f" ❌ 请求失败: {resp.status_code}")
except Exception as e:
print(f" ❌ 错误: {e}")
time.sleep(0.3)
if __name__ == "__main__":
main()

View File

View File

@ -19,7 +19,7 @@ CONFIG = {
"106": {
"base_url": "http://106.75.72.40:7500/api/proxy/tcp",
"primary_auth": "Basic YWRtaW46bGljYWhr",
"x_auth": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJsb2NhbGUiOiJ6aC1jbiIsInZpZXdNb2RlIjoibGlzdCIsInNpbmdsZUNsaWNrIjpmYWxzZSwicGVybSI6eyJhZG1pbiI6dHJ1ZSwiZXhlY3V0ZSI6dHJ1ZSwiY3JlYXRlIjp0cnVlLCJyZW5hbWUiOnRydWUsIm1vZGlmeSI6dHJ1ZSwiZGVsZXRlIjp0cnVlLCJzaGFyZSI6dHJ1ZSwiZG93bmxvYWQiOnRydWV9LCJjb21tYW5kcyI6W10sImxvY2tQYXNzd29yZCI6ZmFsc2UsImhpZGVEb3RmaWxlcyI6ZmFsc2V9LCJleHAiOjE3Njc2Njg3NzgsImlhdCI6MTc2NzY2MTU3OCwiaXNzIjoiRmlsZSBCcm93c2VyIn0.z9zycFSf3XpUDRhGjziUJ-PUeHIsRba23AI6itqXM-w"
"login_payload": {"username": "admin", "password": "licahk", "recaptcha": ""}
},
"82": {
"base_url": "http://82.156.1.111/weather/php",
@ -37,7 +37,6 @@ def add_error(source, name, reason, latest_time="N/A"):
days_diff = "N/A"
if latest_time and latest_time != "N/A":
try:
# 兼容 2026_01_06 和 2026-01-06 格式
clean_date_str = str(latest_time).split()[0].replace('_', '-')
target_date = datetime.strptime(clean_date_str, "%Y-%m-%d").date()
today_date = datetime.now().date()
@ -63,12 +62,12 @@ def find_closest_item(items, is_date_level=True):
scored_items = []
for item in items:
if not isinstance(item, dict): continue
path = item.get('path', '')
if not path: continue
name_val = item.get('name', '')
path_val = item.get('path', '')
target_str = name_val if name_val else path_val.split('/')[-1]
try:
if is_date_level:
date_str = path.split('/')[-1]
current_date = datetime.strptime(date_str, "%Y_%m_%d")
current_date = datetime.strptime(target_str, "%Y_%m_%d")
else:
mod_str = item.get('modified', '')
if mod_str:
@ -76,13 +75,12 @@ def find_closest_item(items, is_date_level=True):
else:
continue
diff = abs((today - current_date.replace(tzinfo=None)).total_seconds())
scored_items.append((diff, item))
scored_items.append((diff, item, target_str))
except:
continue
if not scored_items: return None
scored_items.sort(key=lambda x: x[0])
return scored_items[0][1]
return scored_items[0]
def process_text_content(raw_content):
@ -105,16 +103,28 @@ def save_json(folder, name, data):
json.dump(data, f, indent=4, ensure_ascii=False)
# --- 106 网站逻辑 (强化防御版) ---
# --- 106 网站逻辑 ---
def get_106_dynamic_token(port):
"""为106特定端口站点执行登录获取 Token"""
url = f"http://106.75.72.40:{port}/api/login"
try:
resp = requests.post(url, json=CONFIG["106"]["login_payload"], timeout=10)
if resp.status_code == 200:
return resp.text.strip().replace('"', '')
except:
pass
return None
def run_106_logic():
print("\n>>> 开始处理 106 网站 (FRPS)...")
print("\n>>> 开始处理 106 网站 (FRPS - 修正逻辑)...")
c = CONFIG["106"]
headers = {"Authorization": c["primary_auth"], "x-auth": c["x_auth"], "User-Agent": "Mozilla/5.0"}
today_str = datetime.now().strftime("%Y_%m_%d")
try:
resp = requests.get(c["base_url"], headers=headers, timeout=15)
main_headers = {"Authorization": c["primary_auth"], "User-Agent": "Mozilla/5.0"}
resp = requests.get(c["base_url"], headers=main_headers, timeout=15)
if resp.status_code != 200:
add_error("106网站", "主入口API", f"访问失败: HTTP {resp.status_code}")
return
@ -123,81 +133,97 @@ def run_106_logic():
for item in proxies:
if not isinstance(item, dict): continue
name = item.get('name', 'Unknown')
if not name.endswith('_data'): continue
if not name.lower().endswith('_data'): continue
try:
# 1. 状态预检 - 彻底解决 NoneType 问题
# 1. 状态预检 - 离线拦截逻辑
status_raw = item.get('status', '')
status = str(status_raw).lower().strip() if status_raw else "unknown"
conf = item.get('conf') or {}
port = conf.get('remote_port')
# 离线直接判定,严禁继续访问二级接口
# 如果离线,直接保存并记录错误,不再进行后续 API 访问
if status != 'online':
add_error("106网站", name, f"设备离线 (当前状态: {status})")
save_json(FRPS_DIR, name, item)
continue
# 2. 识别站点类型并进行在线处理
name_up = name.upper()
is_tower_underscore = "TOWER_" in name_up
is_tower_i = "TOWER" in name_up and not is_tower_underscore
if not (is_tower_underscore or is_tower_i): continue
try:
conf = item.get('conf') or {}
port = conf.get('remote_port')
if not port:
add_error("106网站", name, "配置错误: 缺少 remote_port")
continue
# 2. 只有 Online 才进行二级访问
res2 = requests.get(f"http://106.75.72.40:{port}/api/resources/Data/", headers=headers, timeout=10)
# 只有 Online 才获取子站点 Token
token = get_106_dynamic_token(port)
if not token:
add_error("106网站", name, "Token获取失败(登录异常)")
continue
headers = {"Authorization": c["primary_auth"], "x-auth": token, "User-Agent": "Mozilla/5.0"}
# 查找 Data 根目录 (根据类型区分大小写)
api_root = "/api/resources/Data/" if is_tower_underscore else "/api/resources/data/"
res2 = requests.get(f"http://106.75.72.40:{port}{api_root}", headers=headers, timeout=10)
if res2.status_code != 200:
add_error("106网站", name, f"无法打开Data目录 (HTTP {res2.status_code})")
continue
it2 = res2.json().get('items', [])
closest_date = find_closest_item(it2, True)
if not closest_date:
add_error("106网站", name, "Data目录为空")
continue
best_date = find_closest_item(it2, is_date_level=True)
if not best_date or best_date[2] != today_str:
add_error("106网站", name, "未找到今日文件夹", best_date[2] if best_date else "N/A")
if not best_date: continue
path_date = closest_date.get('path', '')
date_val = path_date.split('/')[-1]
date_path = f"{api_root}{best_date[2]}/"
# 记录日期不对的情况,但尝试继续抓取
if date_val != today_str:
add_error("106网站", name, "日期非当天", date_val)
# 3. 访问日期内文件列表
res3 = requests.get(f"http://106.75.72.40:{port}/api/resources{path_date}/", headers=headers,
timeout=10)
# 查找文件夹内最新文件
res3 = requests.get(f"http://106.75.72.40:{port}{date_path}", headers=headers, timeout=10)
it3 = res3.json().get('items', [])
closest_file = find_closest_item(it3, False)
if not closest_file:
add_error("106网站", name, "文件夹内无文件", date_val)
best_file = find_closest_item(it3, is_date_level=False)
if not best_file:
add_error("106网站", name, "文件夹内无文件", best_date[2])
continue
# 4. 读取内容并进行 NoneType 防御
path_csv = closest_file.get('path', '')
res4 = requests.get(f"http://106.75.72.40:{port}/api/resources{path_csv}", headers=headers, timeout=10)
file_item = best_file[1]
full_path = file_item.get('path') or f"{date_path}{file_item.get('name')}"
# 3. 根据类型下载内容
if is_tower_i:
# TowerI 模式:使用 raw 接口获取二进制
raw_url = f"http://106.75.72.40:{port}/api/raw{full_path}"
res4 = requests.get(raw_url, headers=headers, timeout=20)
if res4.status_code == 200:
save_path = os.path.join(FRPS_DIR, f"{name}_{today_str}.bin")
with open(save_path, 'wb') as f:
f.write(res4.content)
print(f"{name} 二进制数据保存成功")
else:
# Tower_ 模式:使用 resources 接口获取 JSON
file_api_url = f"http://106.75.72.40:{port}/api/resources{full_path}"
res4 = requests.get(file_api_url, headers=headers, timeout=20)
file_json = res4.json()
if file_json is None:
add_error("106网站", name, "内容接口返回 Null", date_val)
continue
raw_content = file_json.get('content', '')
if not raw_content:
add_error("106网站", name, "content字段为空", date_val)
save_json(FRPS_DIR, name, {
"status": status,
"latest_path": path_csv,
"content": process_text_content(raw_content)
})
raw_content = file_json.get('content', '') if file_json else None
if raw_content:
save_path = os.path.join(FRPS_DIR, f"{name}_{today_str}.json")
with open(save_path, 'w', encoding='utf-8') as f:
f.write(process_text_content(raw_content))
print(f"{name} JSON数据保存成功")
else:
add_error("106网站", name, "文件内容为空", best_date[2])
except Exception as e:
add_error("106网站", name, f"站点崩溃: {str(e)}")
add_error("106网站", name, f"站点处理崩溃: {str(e)}")
except Exception as e:
add_error("106网站", "全局逻辑", f"主进程崩溃: {str(e)}")
# --- 82 网站逻辑 ---
# --- 82 网站逻辑 (保持原样) ---
def run_82_logic():
print("\n>>> 开始处理 82 网站 (Weather)...")
@ -253,7 +279,6 @@ def export_to_excel():
df = pd.DataFrame(error_logs)
cols = ["数据来源", "站点/代理名称", "错误原因", "日期偏移量", "最新数据时间", "检查时间"]
# 过滤掉 dataframe 中不存在的列,防止报错
df = df[[c for c in cols if c in df.columns]]
df.to_excel(EXCEL_PATH, index=False)
print(f"\n[!] 错误报表已生成至: {EXCEL_PATH} (共 {len(error_logs)} 条)")

8
zhandianxinxi/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

9
zhandianxinxi/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.12 (zhandianxinxi)" />
</component>
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

8
zhandianxinxi/.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/zhandianxinxi.iml" filepath="$PROJECT_DIR$/zhandianxinxi.iml" />
</modules>
</component>
</project>

6
zhandianxinxi/.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.12 (zhandianxinxi)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,3 @@
{
"recommendations": ["Vue.volar"]
}

View File

@ -0,0 +1,5 @@
# Vue 3 + Vite
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 `<script setup>` SFCs, check out the [script setup docs](https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup) to learn more.
Learn more about IDE Support for Vue in the [Vue Docs Scaling up Guide](https://vuejs.org/guide/scaling-up/tooling.html#ide-support).

View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>my-vue-app</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
{
"name": "my-vue-app",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"@element-plus/icons-vue": "^2.1.0",
"axios": "^1.5.1",
"echarts": "^6.0.0",
"element-plus": "^2.3.14",
"vue": "^3.3.4",
"vue-json-viewer": "^3.0.4"
},
"devDependencies": {
"@vitejs/plugin-vue": "4.5.0",
"vite": "4.5.0"
}
}

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,487 @@
<template>
<div class="container">
<el-card shadow="never" class="main-card">
<template #header>
<div class="header-row">
<div class="left-panel">
<h2 class="sys-title">📡 光谱数据监控</h2>
<div class="sys-status">
<span v-if="isRunning" class="status-running">
<el-icon class="is-loading"><Loading /></el-icon> 正在执行同步任务...
</span>
<span v-else class="status-idle">
<el-icon><CircleCheck /></el-icon> 系统就绪 (最后更新: {{ lastCheckTime }})
</span>
</div>
</div>
<div class="header-actions">
<el-button type="primary" :loading="isRunning" @click="handleManualRefresh(false)" round icon="Refresh" :size="isMobile ? 'small' : 'default'">手动同步</el-button>
</div>
</div>
</template>
<div class="status-summary">
<el-tag type="danger" effect="dark" class="res-tag">红色已离线 / 异常 / 滞后>7</el-tag>
<el-tag type="warning" color="#ff8c00" effect="dark" class="res-tag" style="border-color: #ff8c00;">橘色滞后 2-7 </el-tag>
<el-tag type="warning" effect="dark" class="res-tag">黄色滞后 1-2 </el-tag>
<el-tag type="success" effect="dark" class="res-tag">绿色正常且今日已同步</el-tag>
</div>
<div class="toolbar" :class="{ 'mobile-toolbar': isMobile }">
<div class="filter-section">
<el-radio-group v-model="filters.site" :size="isMobile ? 'small' : 'default'">
<el-radio-button value="all">全部</el-radio-button>
<el-radio-button value="106">106 塔上光谱仪</el-radio-button>
<el-radio-button value="82">82 高光谱传感器</el-radio-button>
</el-radio-group>
<el-input
v-model="filters.keyword"
placeholder="搜索设备名称..."
class="search-input"
clearable
/>
</div>
<div class="action-section">
<el-checkbox v-model="showHidden" label="显示屏蔽" border style="margin-right: 10px" :size="isMobile ? 'small' : 'default'"/>
<el-button type="warning" plain :disabled="selectedRows.length === 0" @click="hideSelected" :size="isMobile ? 'small' : 'default'">屏蔽选中</el-button>
</div>
</div>
<el-table
ref="multipleTableRef"
:data="sortedData"
border
height="600"
v-loading="isRunning"
@selection-change="val => selectedRows = val"
:row-class-name="tableRowClassName"
style="width: 100%"
>
<el-table-column type="selection" width="40" align="center" fixed="left" />
<el-table-column label="状态" :width="isMobile ? 90 : 120" align="center">
<template #default="{ row }">
<el-tag :style="getStatusTagStyle(row)" effect="dark" size="small">{{ getStatusLabel(row) }}</el-tag>
</template>
</el-table-column>
<el-table-column label="名称" min-width="180">
<template #default="{ row }">
<div class="name-cell">
<el-link type="primary" underline="hover" @click="showDetails(row)" style="font-weight: bold; font-size: 14px;">
{{ formatDisplayName(row.name) }}
</el-link>
<el-tag v-if="isHidden(row.name)" type="info" size="small" style="margin-left:5px">隐藏</el-tag>
</div>
</template>
</el-table-column>
<el-table-column prop="reason" label="反馈" min-width="150" v-if="!isMobile">
<template #default="{ row }">
<span :style="{ color: getStatusColor(row), fontWeight: 'bold' }">{{ formatReason(row) }}</span>
</template>
</el-table-column>
<el-table-column prop="offset" label="时效" width="80" align="center" v-if="!isMobile"/>
<el-table-column prop="latest_time" label="数据时间" width="170" align="center" />
<el-table-column label="操作" width="70" v-if="showHidden" align="center" fixed="right">
<template #default="{ row }">
<el-button v-if="isHidden(row.name)" type="primary" link @click="restoreDevice(row.name)">恢复</el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<el-drawer
v-model="drawerVisible"
title="设备详情"
:size="isMobile ? '100%' : '80%'"
@opened="initCharts"
direction="rtl"
>
<!-- <div v-if="activeDevice" class="drawer-content">-->
<!-- <div class="info-banner">-->
<!-- <el-descriptions :column="isMobile ? 1 : 4" border size="small">-->
<!-- <el-descriptions-item label="设备名称">{{ formatDisplayName(activeDevice.name) }}</el-descriptions-item>-->
<!-- <el-descriptions-item label="当前状态">-->
<!-- <el-tag size="small" :style="getStatusTagStyle(activeDevice)">{{ getStatusLabel(activeDevice) }}</el-tag>-->
<!-- </el-descriptions-item>-->
<!-- <el-descriptions-item label="数据时间">{{ activeDevice.latest_time }}</el-descriptions-item>-->
<!-- <el-descriptions-item label="检查时间">{{ activeDevice.check_time }}</el-descriptions-item>-->
<!-- </el-descriptions>-->
<!-- </div>-->
<!-- <div class="visual-section">-->
<!-- <h3 class="section-title">-->
<!-- <el-icon><DataLine /></el-icon>-->
<!-- {{ is106Site ? '光谱能量分布 (完整原始数据)' : '高光谱传感器数据 (Up/Down Spec)' }}-->
<!-- </h3>-->
<!-- <div v-if="currentChartModules.length === 0" class="empty-hint"><el-empty description="暂无有效的图表数据" /></div>-->
<!-- <div v-for="(module, index) in currentChartModules" :key="index" class="chart-container">-->
<!-- <div class="chart-header" v-if="is106Site">-->
<!-- <div class="tag-group">-->
<!-- <span class="module-tag">型号: {{ module.model }}</span>-->
<!-- <span class="sn-tag">SN: {{ module.sn }}</span>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div :id="'chart-' + index" class="echart-box" :class="{ 'no-header': !is106Site }"></div>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<sidevueold ref="siderold"></sidevueold>
</el-drawer>
</div>
</template>
<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading, CircleCheck, Refresh, DataLine } from '@element-plus/icons-vue'
import sidevueold from "./sidevueold.vue"
// --- 响应式布局状态 ---
const windowWidth = ref(window.innerWidth)
const isMobile = computed(() => windowWidth.value < 768)
// 窗口大小监听函数
const handleResize = () => {
windowWidth.value = window.innerWidth
// 触发图表重绘
chartInstances.forEach(chart => chart && chart.resize())
}
// --- 状态变量 ---
const rawData = ref([])
const isRunning = ref(false)
const lastCheckTime = ref('N/A')
const selectedRows = ref([])
const showHidden = ref(false)
const drawerVisible = ref(false)
const activeDevice = ref(null)
const filters = reactive({ site: 'all', keyword: '' })
const multipleTableRef = ref()
let chartInstances = [] // 存储图表实例以便resize
// 初始化隐藏列表
const ignoredList = ref(JSON.parse(localStorage.getItem('hide_list') || '[]'))
let autoRefreshTimer = null
// --- 工具函数 ---
const formatSource = (source) => {
if (!source) return ''
const s = source.toString()
if (s.includes('106')) return '106 塔上光谱仪'
if (s.includes('82')) return '82 高光谱传感器'
return s
}
const formatDisplayName = (name) => {
if (!name) return ''
return name.split('_').map(part => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase()).join('_')
}
const parseFlexibleDate = (dateStr) => {
if (!dateStr || dateStr === 'N/A') return null
try {
let cleanStr = dateStr.toString().split('.')[0].replace(/[_/]/g, '-')
const d = new Date(cleanStr)
return isNaN(d.getTime()) ? null : d
} catch { return null }
}
const getHoursDiff = (dateStr) => {
if (!dateStr || dateStr === 'N/A') return 999
const lastDate = parseFlexibleDate(dateStr)
if (!lastDate) return 999
return (new Date() - lastDate) / (1000 * 3600)
}
// --- 业务逻辑 (状态与排序) ---
const getLevel = (row) => {
if (row.status === '已离线' || row.status === '异常') return 4
if (!row.content || row.content === '{}') return 4
const last = parseFlexibleDate(row.latest_time)
if (!last) return 4
const now = new Date()
const days = (now - last) / (1000 * 3600 * 24)
if (days > 7) return 4
if (days > 2) return 3
if (now.getDate() !== last.getDate()) return 2
return 1
}
const getStatusLabel = (row) => {
if (row.status === '已离线') return '已离线'
if (row.status === '异常') return '异常'
const level = getLevel(row)
if (level === 4) return '缺失'
if (level === 3) return '>2天'
if (level === 2) return '昨日'
return '在线'
}
const getStatusColor = (row) => {
const level = getLevel(row)
return ['#909399', '#67C23A', '#E6A23C', '#ff8c00', '#F56C6C'][level]
}
const getStatusTagStyle = (row) => {
const color = getStatusColor(row)
return { backgroundColor: color, borderColor: color, color: 'white', border: 'none' }
}
const formatReason = (row) => {
if (row.reason && row.reason !== '同步成功') return row.reason
const level = getLevel(row)
if (level === 2) return '⚠️ 待今日更新'
return '✅ 同步正常'
}
// --- 隐藏/恢复逻辑 ---
const isHidden = (name) => ignoredList.value.includes(name)
const restoreDevice = (name) => {
if (!name) return
ignoredList.value = ignoredList.value.filter(item => item !== name)
localStorage.setItem('hide_list', JSON.stringify(ignoredList.value))
ElMessage.success('设备已恢复显示')
}
const hideSelected = () => {
if (selectedRows.value.length === 0) return
const namesToHide = selectedRows.value.map(row => row.name)
let count = 0
namesToHide.forEach(name => {
if (!ignoredList.value.includes(name)) {
ignoredList.value.push(name)
count++
}
})
if (count > 0) {
localStorage.setItem('hide_list', JSON.stringify(ignoredList.value))
ElMessage.warning(`已屏蔽 ${count} 个设备`)
if (multipleTableRef.value) multipleTableRef.value.clearSelection()
} else {
ElMessage.info('选中的设备已在屏蔽列表中')
}
}
const siderold = ref(null)
var tempdata=0
const showDetails = (row) => {
activeDevice.value = row
drawerVisible.value = true
nextTick(() => {
// 此时 siderold.value 才有值
// 使用 ?. 防止极个别情况下组件未挂载导致的报错
if (siderold.value) {
siderold.value.loaddata(row)
tempdata++;
} else {
console.warn("子组件尚未挂载")
}
})
}
// --- 过滤与排序 ---
const sortedData = computed(() => {
return rawData.value.filter(d => {
const basicMatch = (filters.site === 'all' || d.source.includes(filters.site)) &&
d.name.toLowerCase().includes(filters.keyword.toLowerCase())
if (showHidden.value) return basicMatch
else return basicMatch && !isHidden(d.name)
}).sort((a, b) => getLevel(b) - getLevel(a))
})
const tableRowClassName = ({ row }) => row.status === '已离线' ? 'offline-row' : ''
// --- 刷新逻辑 ---
const fetchLogs = async () => {
try {
const res = await axios.get('/api/logs')
rawData.value = res.data
if (res.data.length > 0) {
const latest = res.data.reduce((prev, curr) => (prev.check_time > curr.check_time) ? prev : curr)
lastCheckTime.value = latest.check_time
}
} catch (e) {
console.warn("API Error, using mock data for display")
}
}
const checkStatus = async () => {
try {
const res = await axios.get('/api/status')
isRunning.value = res.data.is_running
if (isRunning.value) setTimeout(checkStatus, 2000)
else fetchLogs()
} catch { isRunning.value = false }
}
const handleManualRefresh = async (force = false) => {
const hours = getHoursDiff(lastCheckTime.value)
if (!force && hours < 6) {
try {
await ElMessageBox.confirm(
`数据更新于 ${hours.toFixed(1)} 小时前。后端每日10点自动更新通常无需手动操作。\n是否强制重新爬取`,
'数据尚新', { confirmButtonText: '强制爬取', cancelButtonText: '仅加载最新', type: 'warning' }
)
} catch {
fetchLogs()
ElMessage.success('已加载最新数据库记录')
return
}
}
try {
isRunning.value = true
await axios.post('/api/run')
checkStatus()
ElMessage.success('任务已下发')
} catch {
isRunning.value = false
ElMessage.warning('后台已有任务在运行')
}
}
// --- 图表逻辑 ---
const is106Site = computed(() => activeDevice.value?.source?.includes('106'))
const currentChartModules = computed(() => {
if (!activeDevice.value?.content || activeDevice.value.content === '{}') return []
if (is106Site.value) {
const modules = []
const infoRegex = /FS\d_Info,Model,([^,]+),SN,([^,]+).*?Wavelength,([\d\.,\s]+)/gs
let match
const contentStr = activeDevice.value.content
while ((match = infoRegex.exec(contentStr)) !== null) {
const wavelengths = match[3].split(',').map(Number).filter(n => !isNaN(n))
const series = []
for (let p = 1; p <= 4; p++) {
const dMatch = contentStr.match(new RegExp(`${match[1].trim()}_P${p}[^0-9-]*([\\d\\.,\\s-]+)`, 'i'))
if (dMatch) {
const vals = dMatch[1].split(',').map(v => {
const n = parseFloat(v);
// 修改点 2不再判断 n > 65500直接返回原始值 n
return n;
})
if (vals.some(v => v !== null)) series.push({ name: `P${p}`, data: vals, color: ['#5470c6', '#91cc75', '#fac858', '#ee6666'][p-1] })
}
}
if (series.length) modules.push({ model: match[1], sn: match[2], xAxis: wavelengths, series })
}
return modules
} else {
try {
const d = JSON.parse(activeDevice.value.content)
return d.wavelenth ? [{ title: activeDevice.value.name, xAxis: d.wavelenth, series: [
{ name: 'DownSpec', data: d.downspec, color: '#409EFF' }, { name: 'UpSpec', data: d.upspec, color: '#67C23A' }
]}] : []
} catch { return [] }
}
})
const initCharts = () => {
chartInstances = [] // 清空旧实例引用
nextTick(() => {
currentChartModules.value.forEach((m, i) => {
const dom = document.getElementById(`chart-${i}`)
if (dom) {
if (echarts.getInstanceByDom(dom)) echarts.getInstanceByDom(dom).dispose()
const chart = echarts.init(dom)
chartInstances.push(chart)
chart.setOption({
title: { text: is106Site.value ? `SN: ${m.sn}` : m.title, left: 'center', top: 10, textStyle: { fontSize: isMobile.value ? 14 : 18 } },
tooltip: { trigger: 'axis', confine: true },
legend: { top: 35, type: 'scroll' },
grid: { top: 70, bottom: 30, right: isMobile.value ? 10 : 30, left: isMobile.value ? 40 : 50 },
xAxis: { type: 'category', data: m.xAxis, boundaryGap: false },
yAxis: { type: 'value', min: 'dataMin', max: 'dataMax' },
series: m.series.map(s => ({
name: s.name,
type: 'line',
data: s.data,
connectNulls: false,
smooth: true,
showSymbol: false,
lineStyle: { width: 2, color: s.color },
areaStyle: { opacity: 0.1, color: s.color }
}))
})
}
})
})
}
// --- 生命周期 ---
onMounted(() => {
document.title = "光谱数据监控"
fetchLogs()
window.addEventListener('resize', handleResize)
autoRefreshTimer = setInterval(() => {
if (!isRunning.value) fetchLogs()
}, 300000)
})
onBeforeUnmount(() => {
window.removeEventListener('resize', handleResize)
if (autoRefreshTimer) clearInterval(autoRefreshTimer)
chartInstances.forEach(c => c && c.dispose())
})
</script>
<style scoped>
/* 基础 PC 端样式 */
.container { padding: 20px; max-width: 1400px; margin: 0 auto; background-color: #f5f7fa; min-height: 100vh; transition: all 0.3s; }
.header-row { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
.sys-title { margin: 0; font-size: 22px; color: #303133; font-weight: 600; }
.sys-status { font-size: 13px; color: #909399; margin-top: 5px; }
.status-running { color: #409EFF; font-weight: bold; display: flex; align-items: center; gap: 5px; }
.status-idle { display: flex; align-items: center; gap: 5px; }
.status-summary { margin: 15px 0; display: flex; gap: 10px; flex-wrap: wrap; }
.toolbar { background: #fff; padding: 15px 20px; border-radius: 8px; display: flex; justify-content: space-between; margin-bottom: 20px; border: 1px solid #ebeef5; align-items: center; transition: all 0.3s; }
.filter-section { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
.name-cell { display: flex; align-items: center; flex-wrap: wrap; gap: 5px;}
:deep(.offline-row) { background-color: #fef0f0 !important; }
.drawer-content { padding: 0 20px 20px; }
.info-banner { margin-bottom: 20px; }
.chart-container { margin-bottom: 30px; border: 1px solid #e4e7ed; border-radius: 8px; overflow: hidden; background: #fff; }
.chart-header { background: #fafafa; padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #e4e7ed; }
.echart-box { width: 100%; height: 380px; }
.echart-box.no-header { margin-top: 15px; }
/* 移动端适配 (Screen < 768px) */
@media screen and (max-width: 768px) {
.container { padding: 10px; }
/* 头部调整 */
.header-row { flex-direction: column; align-items: flex-start; }
.left-panel { width: 100%; margin-bottom: 10px; }
.header-actions { width: 100%; display: flex; justify-content: flex-end; }
.sys-title { font-size: 18px; }
/* 状态标签调整 */
.status-summary { gap: 5px; }
.res-tag { font-size: 11px; height: 24px; padding: 0 5px; }
/* 工具栏调整 */
.mobile-toolbar { flex-direction: column; align-items: stretch; padding: 15px 10px; }
.filter-section { flex-direction: column; align-items: stretch; width: 100%; }
.search-input { width: 100% !important; margin-left: 0 !important; margin-top: 5px; }
.action-section {
display: flex;
justify-content: space-between;
margin-top: 15px;
padding-top: 10px;
border-top: 1px dashed #ebeef5;
}
/* Drawer 内部调整 */
.drawer-content { padding: 0 10px 20px; }
.chart-header { flex-direction: column; align-items: flex-start; gap: 5px; }
.echart-box { height: 300px; }
}
</style>

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

View File

@ -0,0 +1,17 @@
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import JsonViewer from 'vue-json-viewer'
const app = createApp(App)
// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
app.use(ElementPlus)
app.use(JsonViewer)
app.mount('#app')

View File

@ -0,0 +1,39 @@
<script setup>
import {DataLine} from "@element-plus/icons-vue";
</script>
<template>
<div v-if="activeDevice" class="drawer-content">
<div class="info-banner">
<el-descriptions :column="isMobile ? 1 : 4" border size="small">
<el-descriptions-item label="设备名称">{{ formatDisplayName(activeDevice.name) }}</el-descriptions-item>
<el-descriptions-item label="当前状态">
<el-tag size="small" :style="getStatusTagStyle(activeDevice)">{{ getStatusLabel(activeDevice) }}</el-tag>
</el-descriptions-item>
<el-descriptions-item label="数据时间">{{ activeDevice.latest_time }}</el-descriptions-item>
<el-descriptions-item label="检查时间">{{ activeDevice.check_time }}</el-descriptions-item>
</el-descriptions>
</div>
<div class="visual-section">
<h3 class="section-title">
<el-icon><DataLine /></el-icon>
{{ is106Site ? '光谱能量分布 (完整原始数据)' : '高光谱传感器数据 (Up/Down Spec)' }}
</h3>
<div v-if="currentChartModules.length === 0" class="empty-hint"><el-empty description="暂无有效的图表数据" /></div>
<div v-for="(module, index) in currentChartModules" :key="index" class="chart-container">
<div class="chart-header" v-if="is106Site">
<div class="tag-group">
<span class="module-tag">型号: {{ module.model }}</span>
<span class="sn-tag">SN: {{ module.sn }}</span>
</div>
</div>
<div :id="'chart-' + index" class="echart-box" :class="{ 'no-header': !is106Site }"></div>
</div>
</div>
</div>
</template>
<style scoped>
</style>

View File

@ -0,0 +1,79 @@
<script>
import {DataLine} from "@element-plus/icons-vue";
import axios from 'axios'
export default {
name: "sidevueold",
components: {DataLine},
data(){
return{
activeDevice:{},
bbb:0,
date:"2022-10-11"
}
},
mounted() {
console.log("hello from 111")
},
props:{
id:0
},
methods:{
loaddata(a){
this.bbb=a;
console.log(a);
},
loadhistorydata(){
var dateselect=this.date;
//去后端获取数据 getdata(dateselect)
console.log("im getting data form back "+dateselect)
}
},
unmounted() {
}
}
</script>
<template>
<input type="date" v-model="date"/>
<button @click="loadhistorydata">获取历史数据</button>
{{bbb}}
<!-- <div v-if="activeDevice" class="drawer-content">-->
<!-- <div class="info-banner">-->
<!-- <el-descriptions :column="isMobile ? 1 : 4" border size="small">-->
<!-- <el-descriptions-item label="设备名称">{{ formatDisplayName(activeDevice.name) }}</el-descriptions-item>-->
<!-- <el-descriptions-item label="当前状态">-->
<!-- <el-tag size="small" :style="getStatusTagStyle(activeDevice)">{{ getStatusLabel(activeDevice) }}</el-tag>-->
<!-- </el-descriptions-item>-->
<!-- <el-descriptions-item label="数据时间">{{ activeDevice.latest_time }}</el-descriptions-item>-->
<!-- <el-descriptions-item label="检查时间">{{ activeDevice.check_time }}</el-descriptions-item>-->
<!-- </el-descriptions>-->
<!-- </div>-->
<!-- <div class="visual-section">-->
<!-- <h3 class="section-title">-->
<!-- <el-icon><DataLine /></el-icon>-->
<!-- {{ is106Site ? '光谱能量分布 (完整原始数据)' : '高光谱传感器数据 (Up/Down Spec)' }}-->
<!-- </h3>-->
<!-- <div v-if="currentChartModules.length === 0" class="empty-hint"><el-empty description="暂无有效的图表数据" /></div>-->
<!-- <div v-for="(module, index) in currentChartModules" :key="index" class="chart-container">-->
<!-- <div class="chart-header" v-if="is106Site">-->
<!-- <div class="tag-group">-->
<!-- <span class="module-tag">型号: {{ module.model }}</span>-->
<!-- <span class="sn-tag">SN: {{ module.sn }}</span>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div :id="'chart-' + index" class="echart-box" :class="{ 'no-header': !is106Site }"></div>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
</template>
<style scoped>
</style>

View File

@ -0,0 +1,79 @@
:root {
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.card {
padding: 2em;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}

View File

@ -0,0 +1,30 @@
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
// --- 强烈建议新增这一行 ---
// 这确保 index.html 引用 css/js 时使用相对路径,
// 避免 Flask 托管时出现找不到文件的 404 错误。
base: './',
plugins: [vue()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
// --- 关于这段 server 配置 ---
// 这里的配置仅在你自己电脑上写代码(npm run dev)时有效。
// 打包(npm run build)后,前端请求会直接发给同源的 Flask
// 所以这里填什么 IP 对打包后的程序没有影响,不用改。
server: {
proxy: {
'/api': {
target: 'http://127.0.0.1:5000',
changeOrigin: true
}
}
}
})