#!/usr/bin/env python3 """ 调试当前活跃的监控器 """ import sys import os import datetime sys.path.append(os.path.dirname(__file__)) from influx_service import InfluxService, InfluxConnectionParams from config_model import AppConfig from pathlib import Path def check_recent_status_changes(): """检查最近的状态变化""" print("🔍 检查最近的状态变化") # 加载配置 config_path = Path("default.json") config = AppConfig.load(config_path) # 创建InfluxDB服务 params = InfluxConnectionParams( url=config.influx.url, org=config.influx.org, token=config.influx.token ) service = InfluxService(params) bucket = getattr(config.influx, 'bucket', 'PCM') measurement = getattr(config.influx, 'measurement', 'experiment_status') try: # 查询最近30分钟的数据 df = service.query( bucket=bucket, measurement=measurement, fields=['status'], filters={}, time_range="-30m" ) if df.empty: print("❌ 最近30分钟没有数据") return [] print(f"✅ 找到 {len(df)} 条数据") # 按时间排序 if '_time' in df.columns and '_value' in df.columns: df_sorted = df.sort_values('_time') print("📊 最近的状态数据:") status_changes = [] prev_value = None for _, row in df_sorted.iterrows(): # 转换为本地时间 time_utc = row['_time'] time_local = time_utc.replace(tzinfo=datetime.timezone.utc).astimezone() time_str = time_local.strftime('%H:%M:%S') value = str(row['_value']) if prev_value is None: print(f" {time_str}: 初始状态 = {value}") elif prev_value != value: print(f" {time_str}: 状态变化 {prev_value} -> {value} ⚡") status_changes.append({ 'time': time_local, 'from': prev_value, 'to': value }) else: print(f" {time_str}: 状态保持 = {value}") prev_value = value return status_changes except Exception as e: print(f"❌ 查询失败: {e}") return [] def check_monitor_configuration(): """检查监控器配置""" print("\n🔧 检查监控器配置") # 加载配置 config_path = Path("default.json") config = AppConfig.load(config_path) print("📋 InfluxDB配置:") print(f" URL: {config.influx.url}") print(f" Org: {config.influx.org}") print(f" Token: {config.influx.token[:20]}..." if config.influx.token else " Token: N/A") print(f" Bucket: {getattr(config.influx, 'bucket', 'N/A')}") print(f" Measurement: {getattr(config.influx, 'measurement', 'N/A')}") # 检查全局参数中的工单号 work_order_no = config.globalParameters.parameters.get('work_order_no', 'N/A') print(f" 当前工单号: {work_order_no}") return { 'bucket': getattr(config.influx, 'bucket', 'PCM'), 'measurement': getattr(config.influx, 'measurement', 'experiment_status'), 'work_order_no': work_order_no } def simulate_monitor_logic(status_changes, config): """模拟监控器逻辑""" print("\n🤖 模拟监控器检测逻辑") if not status_changes: print("❌ 没有状态变化,监控器不会触发") return print("🔍 分析状态变化:") for change in status_changes: time_str = change['time'].strftime('%H:%M:%S') from_state = change['from'] to_state = change['to'] print(f" {time_str}: {from_state} -> {to_state}") # 检查是否匹配监控器的触发条件 if from_state == '0' and to_state == '1': print(f" 🟢 应该触发实验开始 (0->1)") elif from_state == '1' and to_state == '0': print(f" 🔴 应该触发实验结束 (1->0)") else: print(f" ⚪ 其他状态变化,不触发") def check_database_records(): """检查数据库中的实验记录""" print("\n💾 检查数据库中的实验记录") import sqlite3 try: # 连接数据库 db_path = "experiments.db" if not os.path.exists(db_path): print("❌ 数据库文件不存在") return conn = sqlite3.connect(db_path) cursor = conn.cursor() # 查询最近的实验记录 cursor.execute(""" SELECT id, work_order_no, start_ts, end_ts, created_at FROM experiments ORDER BY id DESC LIMIT 5 """) records = cursor.fetchall() if not records: print("❌ 数据库中没有实验记录") else: print("📊 最近的实验记录:") for record in records: exp_id, work_order, start_ts, end_ts, created_at = record status = "进行中" if start_ts and not end_ts else "已完成" if end_ts else "未开始" print(f" ID:{exp_id} 工单:{work_order} 状态:{status}") if start_ts: print(f" 开始: {start_ts}") if end_ts: print(f" 结束: {end_ts}") conn.close() except Exception as e: print(f"❌ 检查数据库失败: {e}") def main(): print("活跃监控器调试工具") print("=" * 40) # 1. 检查最近的状态变化 status_changes = check_recent_status_changes() # 2. 检查监控器配置 config = check_monitor_configuration() # 3. 模拟监控器逻辑 simulate_monitor_logic(status_changes, config) # 4. 检查数据库记录 check_database_records() print("\n💡 诊断建议:") if status_changes: print("✅ 检测到状态变化,监控器应该能够响应") print("🔍 如果没有更新,可能的原因:") print(" 1. 监控器没有正确启动") print(" 2. 监控器配置有误") print(" 3. 数据库更新失败") print(" 4. 界面刷新问题") else: print("❌ 没有检测到状态变化") print("💡 请确保:") print(" 1. 数据写入成功") print(" 2. 时间范围正确") print(" 3. 字段名称匹配") if __name__ == "__main__": main()