This commit is contained in:
张成
2025-12-16 04:39:53 +08:00
parent 8506d974c5
commit a262fb7ff7
2 changed files with 271 additions and 0 deletions

View File

@@ -582,6 +582,16 @@ class TaskQueue {
{ where: { id: task.id } }
);
// 通知客户端任务状态变更
await this.notifyTaskStatusChange(task.sn_code, {
taskId: task.id,
taskName: task.taskName,
taskType: task.taskType,
status: 'running',
progress: 0,
startTime: task.startTime
});
// 使用注册的任务处理器执行任务
const handler = this.taskHandlers.get(task.taskType);
if (!handler) {
@@ -617,6 +627,16 @@ class TaskQueue {
{ where: { id: task.id } }
);
// 通知客户端任务状态变更
await this.notifyTaskStatusChange(task.sn_code, {
taskId: task.id,
taskName: task.taskName,
taskType: task.taskType,
status: 'completed',
progress: 100,
endTime: task.endTime
});
console.log(`[任务队列] 设备 ${task.sn_code} 任务执行成功: ${task.taskName} (耗时: ${task.duration}ms)`);
} catch (error) {
@@ -650,6 +670,17 @@ class TaskQueue {
},
{ where: { id: task.id } }
);
// 通知客户端任务状态变更
await this.notifyTaskStatusChange(task.sn_code, {
taskId: task.id,
taskName: task.taskName,
taskType: task.taskType,
status: 'failed',
progress: 0,
errorMessage: task.errorMessage,
endTime: task.endTime
});
} catch (dbError) {
console.error(`[任务队列] 更新任务失败状态到数据库失败:`, dbError);
}
@@ -994,6 +1025,35 @@ class TaskQueue {
return null;
}
}
/**
* 通知客户端任务状态变更
* @param {string} sn_code - 设备SN码
* @param {object} taskData - 任务数据
*/
async notifyTaskStatusChange(sn_code, taskData) {
try {
const mqttClient = await this.getMqttClient();
if (!mqttClient) {
return; // MQTT客户端不可用静默失败
}
// 通过MQTT发布任务状态变更通知
// 主题格式: task_status_{sn_code}
const topic = `task_status_${sn_code}`;
const message = JSON.stringify({
action: 'task_status_update',
data: taskData,
timestamp: new Date().toISOString()
});
await mqttClient.publish(topic, message);
console.log(`[任务队列] 已通知客户端任务状态变更: ${sn_code} - ${taskData.taskName || taskData.taskType || '未知任务'} (${taskData.status})`);
} catch (error) {
// 通知失败不影响任务执行,只记录日志
console.warn(`[任务队列] 通知客户端任务状态变更失败:`, error.message);
}
}
}
// 导出单例