更新了配置参数保存,删除了重启设备方法。

This commit is contained in:
root 2025-09-27 15:09:22 +08:00
parent ab43cb6767
commit 38fc3abcf2
6 changed files with 160 additions and 85 deletions

View File

@ -1551,6 +1551,73 @@ class DatabaseManager:
logger.error(f'设置系统配置失败: {e}') logger.error(f'设置系统配置失败: {e}')
raise raise
def is_empty_session(self, session_id: str) -> bool:
"""检查是否为空白会话
空白会话的条件
1. status 'created'
2. screen_video_path 为空
3. detection_data 表中没有对应的数据
Args:
session_id: 会话ID
Returns:
bool: True表示是空白会话False表示不是
"""
conn = self.get_connection()
cursor = conn.cursor()
try:
# 检查会话状态和screen_video_path
cursor.execute('''
SELECT status, screen_video_path
FROM detection_sessions
WHERE id = ?
''', (session_id,))
session_row = cursor.fetchone()
if not session_row:
logging.info(f"[is_empty_session] 会话 {session_id} 不存在")
return False # 会话不存在
session_data = dict(session_row)
status = session_data.get('status')
screen_video_path = session_data.get('screen_video_path')
logging.info(f"[is_empty_session] 会话 {session_id} 状态检查: status='{status}', screen_video_path='{screen_video_path}'")
# 检查条件1status是否为created
if status != 'checking':
logging.info(f"[is_empty_session] 会话 {session_id} 状态不是'checking',当前状态: '{status}' - 不是空白会话")
return False
# 检查条件2screen_video_path是否为空
if screen_video_path and screen_video_path.strip():
logging.info(f"[is_empty_session] 会话 {session_id} 已有录屏路径: '{screen_video_path}' - 不是空白会话")
return False
logging.info(f"[is_empty_session] 会话 {session_id} 通过状态和录屏路径检查,继续检查检测数据")
# 检查条件3detection_data表中是否有对应数据
cursor.execute('''
SELECT COUNT(*) as count
FROM detection_data
WHERE session_id = ?
''', (session_id,))
count_row = cursor.fetchone()
data_count = count_row['count'] if count_row else 0
logging.info(f"[is_empty_session] 会话 {session_id} 检测数据数量: {data_count}")
# 如果没有检测数据,则认为是空白会话
return data_count == 0
except Exception as e:
logger.error(f'检查空白会话失败: {e}')
return False
def close(self): def close(self):
"""关闭数据库连接""" """关闭数据库连接"""
if self.connection: if self.connection:

View File

@ -733,7 +733,7 @@ class ConfigManager:
self.logger.info("所有设备配置设置成功") self.logger.info("所有设备配置设置成功")
return { return {
'success': True, 'success': True,
'message': '所有设备配置设置成功', 'message': '相机参数设置成功。重启软件系统生效!',
'results': results, 'results': results,
'updated_configs': self.get_all_device_configs() 'updated_configs': self.get_all_device_configs()
} }

View File

@ -388,7 +388,8 @@ class AppServer:
'name': user['name'], 'name': user['name'],
'role': 'admin' if user['user_type'] == 'admin' else 'user', 'role': 'admin' if user['user_type'] == 'admin' else 'user',
'user_type': user['user_type'], 'user_type': user['user_type'],
'avatar': '' 'avatar': '',
'phone': user['phone']
} }
# 生成token实际项目中应使用JWT等安全token # 生成token实际项目中应使用JWT等安全token
@ -854,7 +855,7 @@ class AppServer:
}), 400 }), 400
# 验证数据格式 # 验证数据格式
supported_devices = ['imu', 'pressure', 'camera', 'femtobolt'] supported_devices = ['camera', 'femtobolt','imu','pressure']
for device_name in data.keys(): for device_name in data.keys():
if device_name not in supported_devices: if device_name not in supported_devices:
return jsonify({ return jsonify({
@ -865,58 +866,58 @@ class AppServer:
result = self.config_manager.set_all_device_configs(data) result = self.config_manager.set_all_device_configs(data)
# 如果配置设置成功,异步重启设备数据推送 # 如果配置设置成功,异步重启设备数据推送
if result['success']: # if result['success']:
def restart_devices_async(): # def restart_devices_async():
"""异步重启设备数据推送""" # """异步重启设备数据推送"""
try: # try:
self.logger.info("设备配置更新成功,异步重启设备数据推送...") # self.logger.info("设备配置更新成功,异步重启设备数据推送...")
# 先停止当前的数据推送 # # 先停止当前的数据推送
if self.is_pushing_data: # if self.is_pushing_data:
self.stop_device_push_data() # self.stop_device_push_data()
time.sleep(1) # 等待停止完成 # time.sleep(1) # 等待停止完成
# 为每个设备管理器重新加载配置 # # 为每个设备管理器重新加载配置
self.logger.info("重新加载设备配置...") # self.logger.info("重新加载设备配置...")
reload_results = [] # reload_results = []
for device_name, manager in self.device_managers.items(): # for device_name, manager in self.device_managers.items():
if manager is not None and hasattr(manager, 'reload_config'): # if manager is not None and hasattr(manager, 'reload_config'):
try: # try:
success = manager.reload_config() # success = manager.reload_config()
reload_results.append(f"{device_name}: {'成功' if success else '失败'}") # reload_results.append(f"{device_name}: {'成功' if success else '失败'}")
self.logger.info(f"{device_name}设备配置重新加载{'成功' if success else '失败'}") # self.logger.info(f"{device_name}设备配置重新加载{'成功' if success else '失败'}")
except Exception as e: # except Exception as e:
reload_results.append(f"{device_name}: 异常 - {str(e)}") # reload_results.append(f"{device_name}: 异常 - {str(e)}")
self.logger.error(f"{device_name}设备配置重新加载异常: {e}") # self.logger.error(f"{device_name}设备配置重新加载异常: {e}")
else: # else:
reload_results.append(f"{device_name}: 跳过管理器未初始化或不支持reload_config") # reload_results.append(f"{device_name}: 跳过管理器未初始化或不支持reload_config")
self.logger.info(f"配置重新加载结果: {'; '.join(reload_results)}") # self.logger.info(f"配置重新加载结果: {'; '.join(reload_results)}")
# 重新启动设备数据推送 # # 重新启动设备数据推送
self.start_device_push_data() # self.start_device_push_data()
self.logger.info("设备配置更新并重启数据推送完成") # self.logger.info("设备配置更新并重启数据推送完成")
# 通过SocketIO通知前端重启完成 # # 通过SocketIO通知前端重启完成
self.socketio.emit('device_restart_complete', { # self.socketio.emit('device_restart_complete', {
'status': 'success', # 'status': 'success',
'message': '设备重启完成', # 'message': '设备重启完成',
'reload_results': reload_results # 'reload_results': reload_results
}, namespace='/devices') # }, namespace='/devices')
except Exception as restart_error: # except Exception as restart_error:
self.logger.error(f"重启设备数据推送失败: {restart_error}") # self.logger.error(f"重启设备数据推送失败: {restart_error}")
# 通过SocketIO通知前端重启失败 # # 通过SocketIO通知前端重启失败
self.socketio.emit('device_restart_complete', { # self.socketio.emit('device_restart_complete', {
'status': 'error', # 'status': 'error',
'message': f'设备重启失败: {str(restart_error)}' # 'message': f'设备重启失败: {str(restart_error)}'
}, namespace='/devices') # }, namespace='/devices')
# 启动异步线程执行重启操作 # # 启动异步线程执行重启操作
restart_thread = threading.Thread(target=restart_devices_async) # restart_thread = threading.Thread(target=restart_devices_async)
restart_thread.daemon = True # restart_thread.daemon = True
restart_thread.start() # restart_thread.start()
result['message'] = result.get('message', '') + ' 设备正在后台重启中,请稍候...' # result['message'] = result.get('message', '') + ' 设备正在后台重启中,请稍候...'
status_code = 200 if result['success'] else 400 status_code = 200 if result['success'] else 400
return jsonify(result), status_code return jsonify(result), status_code
@ -1009,7 +1010,6 @@ class AppServer:
if not self.db_manager or not self.device_coordinator: if not self.db_manager or not self.device_coordinator:
self.logger.error('数据库管理器或设备管理器未初始化') self.logger.error('数据库管理器或设备管理器未初始化')
return jsonify({'success': False, 'error': '数据库管理器或设备管理器未初始化'}), 500 return jsonify({'success': False, 'error': '数据库管理器或设备管理器未初始化'}), 500
if not session_id: if not session_id:
self.logger.error('缺少会话ID') self.logger.error('缺少会话ID')
return jsonify({ return jsonify({
@ -1017,40 +1017,40 @@ class AppServer:
'error': '缺少会话ID' 'error': '缺少会话ID'
}), 400 }), 400
# 获取请求数据中的duration参数 if self.db_manager.is_empty_session(session_id):
data = flask_request.get_json() or {} # 删除空白会话
duration = data.get('duration') self.db_manager.delete_detection_session(session_id)
self.logger.info(f'已删除空白会话: {session_id}')
# 如果提供了duration更新到数据库
if duration is not None and isinstance(duration, (int, float)):
try:
self.db_manager.update_session_duration(session_id, int(duration))
self.logger.info(f'更新会话持续时间: {session_id} -> {duration}')
except Exception as duration_error:
self.logger.error(f'更新会话持续时间失败: {duration_error}')
# # 停止设备连接监控
# if self.device_coordinator:
# try:
# self.device_coordinator.stop_all_connection_monitor()
# self.logger.info('检测停止,设备连接监控已停止')
# except Exception as monitor_error:
# self.logger.error(f'停止设备连接监控失败: {monitor_error}')
success = self.db_manager.update_session_status(session_id, 'completed')
if success:
self.logger.info(f'检测会话已停止 - 会话ID: {session_id}')
return jsonify({ return jsonify({
'success': True, 'success': True,
'message': '检测已停止' 'message': '空白会话已删除'
}) })
else: else:
self.logger.error('停止检测失败,更新会话状态失败') # 正常会话的停止流程
return jsonify({ # 如果提供了duration更新到数据库
'success': False, data = flask_request.get_json() or {}
'error': '停止检测失败' duration = data.get('duration')
}), 500 if duration is not None and isinstance(duration, (int, float)):
try:
self.db_manager.update_session_duration(session_id, int(duration))
self.logger.info(f'更新会话持续时间: {session_id} -> {duration}')
except Exception as duration_error:
self.logger.error(f'更新会话持续时间失败: {duration_error}')
# 更新会话状态为已完成
success = self.db_manager.update_session_status(session_id, 'completed')
if success:
self.logger.info(f'检测会话已停止 - 会话ID: {session_id}')
return jsonify({
'success': True,
'message': '检测已停止'
})
else:
self.logger.error('停止检测失败,更新会话状态失败')
return jsonify({
'success': False,
'error': '停止检测失败'
}), 500
except Exception as e: except Exception as e:
self.logger.error(f'停止检测失败: {e}', exc_info=True) self.logger.error(f'停止检测失败: {e}', exc_info=True)
return jsonify({'success': False, 'error': str(e)}), 500 return jsonify({'success': False, 'error': str(e)}), 500
@ -1664,7 +1664,8 @@ class AppServer:
is_connected: 连接状态 is_connected: 连接状态
""" """
self.logger.info(f'设备状态变化: {device_name} -> {"已连接" if is_connected else "未连接"}') self.logger.info(f'设备状态变化: {device_name} -> {"已连接" if is_connected else "未连接"}')
self.broadcast_device_status(device_name, is_connected) self.broadcast_device_status(device_name, is_connected)
def _detection_worker(self, detection_id, duration): def _detection_worker(self, detection_id, duration):

View File

@ -1742,7 +1742,7 @@ const handleBeforeUnload = (event) => {
} }
// //
// stopDetection() stopDetection()
// WebSocket // WebSocket
disconnectWebSocket() disconnectWebSocket()
@ -1924,7 +1924,7 @@ onUnmounted(() => {
stopRecord() stopRecord()
} }
// stopDetection() stopDetection()
// WebSocket // WebSocket
disconnectWebSocket() disconnectWebSocket()

View File

@ -210,9 +210,16 @@
</style> </style>
<style> <style>
.userInfoviewDialog{
background-color: #323232 !important;
}
.userInfoviewDialog .el-input__inner{ .userInfoviewDialog .el-input__inner{
color: #fff !important; color: #fff !important;
-webkit-text-fill-color: #fff !important; -webkit-text-fill-color: #fff !important;
background-color: #000 !important; }
.userInfoviewDialog .el-input.is-disabled .el-input__wrapper{
background-color: rgba(36, 36, 36, 1);
box-shadow: 0 0 0 1px transparent inset;
border-color: transparent !important;
} }
</style> </style>

View File

@ -4,8 +4,8 @@
<!-- 顶部导航 --> <!-- 顶部导航 -->
<Header v-if="isHeader == false" /> <Header v-if="isHeader == false" />
<div class="nav-container"> <div class="nav-container">
<div class="nav-container-title" @click="goBack"> <div class="nav-container-title">
<img src="@/assets/svg/goback.svg" alt=""> <img src="@/assets/svg/goback.svg" alt="" v-if="isHeader == false" @click="goBack">
<div style="margin-left: 20px;"> <div style="margin-left: 20px;">
患者档案 - {{ patient?.name || '未知' }} (ID: {{ patient?.id || '未知' }}) 患者档案 - {{ patient?.name || '未知' }} (ID: {{ patient?.id || '未知' }})
</div> </div>