fix: 读取模型

This commit is contained in:
wangzhongjie 2025-10-13 10:55:15 +08:00
parent 8bc5e3d975
commit 2c2cb5b829
3 changed files with 142 additions and 52 deletions

View File

@ -225,7 +225,9 @@ const goJudgeVoice = async (sound: JudgeSound, avPlayer: VoiceAnnounce) => {
}
}
/**
* 人工操作项目
*/
export const SetJudgeItem = async (itemno: string, type: 1 | 2) => {
await examJudgeArtificialItem(Number(itemno), type);
const str = JSON.stringify({
@ -357,7 +359,6 @@ const changeExamStatus = async (event: number, xmdm: number, kf: MarkRule[], jud
const checkExamIsEnd = async (judgeUI: JudgeUI, that: JudgeBusiness, isManual?: boolean) => {
dConsole.log(JudgeTag, "校验考试是否结束")
const totalScore = Number(judgeUI.totalScore)
const judgeConfigObj = judgeUI.judgeConfigObj
const examMileage = Number(judgeUI.examMileage)
const passingScore = Number(judgeUI.passingScore)
if (that.isExamEnd) {

View File

@ -1,5 +1,5 @@
//开始评判
import { JudgeConfig, JudgeTag } from '../../config';
import { GlobalConfig, JudgeConfig, JudgeTag } from '../../config';
import {
BaseInfoType,
CARINFO,
@ -33,11 +33,12 @@ import {
examJudgeSetRealExamCallback,
examJudgeVersion
} from './JudgeSDKUtils';
import FileModel from '../judgeSDK/utils/fileModel';
import JudgeBusiness from './JudgeBusiness';
import { saveStartRecordVideo } from '../../utils/Video';
import router from '@ohos.router';
import systemTime from '@ohos.systemTime';
import { ReadFileContent } from '../../utils/Common';
import { BusinessError } from '@ohos.base';
export const JudgeStartFn = async (callBack: Function, judgeUI: JudgeUI, that: JudgeBusiness) => {
const name = judgeUI.name
@ -182,7 +183,7 @@ const GetJudgeInitData = async (context: common.UIAbilityContext, markRuleListOb
if (examSubject == '2' && itemInfoObj) {
allitems = Reflect.ownKeys(itemInfoObj).map(cdsbKey => {
const cdsb: CDSBInfo = Reflect.get(itemInfoObj, cdsbKey);
const model = GetModelData(`${examType}/${cdsb.modelKey}.txt`, context)
const model = GetModelData(`${examType}/${cdsb.modelKey}.txt`)
const temp: ItemInfo = {
xmdm: cdsb?.xmdm || 0,
xmxh: cdsb?.xmxh || "",
@ -206,7 +207,7 @@ const GetJudgeInitData = async (context: common.UIAbilityContext, markRuleListOb
kscx: carType,
cxcode: '1',
name: carName,
carmodel: GetModelData(`${examType}/${carType}.txt`, context) || "",
carmodel: GetModelData(`${examType}/${carType}.txt`) || "",
allitems,
iteminfo: [],
systemparm: systemparmArr,
@ -223,8 +224,8 @@ const GetJudgeInitData = async (context: common.UIAbilityContext, markRuleListOb
map_point_item: mapPointItemArr,
//科目三暂时为空
iteminfo: [],
roads: GetModelData('km3/Roads.txt', context) || "",
sharps: GetModelData('km3/Sharps.txt', context) || ""
roads: GetModelData('km3/Roads.txt') || "",
sharps: GetModelData('km3/Sharps.txt') || ""
};
initInfo.map_point = km3Config.map_point
initInfo.map_point_item = km3Config.map_point_item
@ -237,13 +238,16 @@ const GetJudgeInitData = async (context: common.UIAbilityContext, markRuleListOb
return initInfo
}
export const GetModelData = (modelName: string, context: common.UIAbilityContext): string => {
try {
return new FileModel(context).getModelContent(JudgeConfig.modelPath, modelName);
} catch (e) {
// 可根据实际需求,返回空字符串或抛出异常
/**
* 获取模型数据
*/
export const GetModelData = (modelName: string): string => {
ReadFileContent(GlobalConfig.modelPath + "/" + modelName).then(res => {
return res
}).catch((e: BusinessError) => {
dConsole.error(JudgeTag, `获取模型数据失败: ${modelName}`, e.message)
return '';
}
return "";
})
return ""
};

View File

@ -4,6 +4,37 @@ import { dConsole } from '../../utils/LogWorker';
import http from '@ohos.net.http';
import Request from '../../utils/Request';
/**
* 定义批次进度更新时的回调函数类型
* @param totalTasks 本批次总任务数
* @param completedTasks 已完成任务数 (成功 + 失败)
* @param successfulTasks 成功完成的任务数
* @param failedTasks 失败的任务数
* @param progressPercentage 当前进度百分比 (0-100)
*/
export type OnBatchProgressUpdateCallback = (
totalTasks: number,
completedTasks: number,
successfulTasks: number,
failedTasks: number,
progressPercentage: number
) => void;
/**
* 定义所有任务完成时的回调函数类型
* @param totalTasks 本批次总任务数
* @param completedTasks 已完成任务数 (成功 + 失败)
* @param successfulTasks 成功完成的任务数
* @param failedTasks 失败的任务数
*/
export type OnAllTasksCompletedCallback = (
totalTasks: number,
completedTasks: number,
successfulTasks: number,
failedTasks: number
) => void;
export class ProcessDataTaskPool {
private queue: RegulatoryInterfaceParams[] = [];
private isProcessing: boolean = false;
@ -13,10 +44,45 @@ export class ProcessDataTaskPool {
private readonly minProcessingTime = 2000;
/** 记录每个任务的开始处理时间 */
private taskStartTime: number = 0;
/** 批次进度更新时的回调函数 */
private onBatchProgressUpdateCallback: OnBatchProgressUpdateCallback | null = null;
/** 所有任务完成时的回调函数 (批次) */
private onAllTasksCompletedCallback: OnAllTasksCompletedCallback | null = null;
// 用于跟踪批次任务完成情况
private totalTasksInCurrentBatch: number = 0;
private completedTasksInCurrentBatch: number = 0;
private successfulTasksInCurrentBatch: number = 0;
private failedTasksInCurrentBatch: number = 0;
/**
* 设置批次进度更新时的回调函数
* @param callback 回调函数
*/
public setOnBatchProgressUpdateCallback(callback: OnBatchProgressUpdateCallback): void {
this.onBatchProgressUpdateCallback = callback;
}
/**
* 设置所有任务完成时的回调函数
* @param callback 回调函数
*/
public setOnAllTasksCompletedCallback(callback: OnAllTasksCompletedCallback): void {
this.onAllTasksCompletedCallback = callback;
}
/**
* 添加任务到队列。
* 注意:为了正确追踪批次,通常建议一次性添加一个批次的所有任务。
* 如果在处理过程中动态添加任务,会影响 `totalTasksInCurrentBatch` 的准确性,
* 进而影响 `onAllTasksCompletedCallback` 的触发时机和进度计算。
* @param dataItem 任务数据
*/
public addTask(dataItem: RegulatoryInterfaceParams): void {
console.info(`[Queue] 新任务已添加: ${JSON.stringify(dataItem)},当前队列长度: ${this.queue.length + 1}`);
this.queue.push(dataItem); // 将任务添加到队尾
// 每次添加任务,增加当前批次的总任务数
this.totalTasksInCurrentBatch++;
this.triggerProcessing(); // 尝试启动处理流程
}
@ -29,7 +95,6 @@ export class ProcessDataTaskPool {
console.log('[Queue] 处理器正在运行中,新任务将在稍后被处理。');
return;
}
// [优化] 直接调用 async 函数,它会立即返回一个 Promise不会阻塞当前执行流效果与 Promise.resolve().then() 相同但更简洁。
this.processQueue();
}
@ -44,7 +109,6 @@ export class ProcessDataTaskPool {
try {
console.log(`[Queue] 开始处理任务: ${JSON.stringify(taskData)}`);
// 预先记录将要处理的数据
const obj: WuxiExamType = {
xtlb: taskData.xtlb,
jkxlh: taskData.jkxlh,
@ -55,34 +119,43 @@ export class ProcessDataTaskPool {
};
dConsole.writeProcessData(ProcessDataEnumType.WuxiExam, JSON.stringify(obj));
// 此方法若成功则正常返回,若永久失败则会抛出错误
await this.processSingleTaskWithRetries(taskData);
// 任务成功,将其从队列中移除
// 任务成功
this.queue.shift();
console.log(`[Queue] ✅ 任务处理成功,已从队列移除。剩余任务: ${this.queue.length}`);
// 计算任务实际耗时
const elapsedTime = Date.now() - this.taskStartTime;
// 如果处理时间小于最小要求时间,则延迟剩余时间
if (elapsedTime < this.minProcessingTime) {
const delayTime = this.minProcessingTime - elapsedTime;
console.log(`[Queue] 任务处理耗时 ${elapsedTime}ms需要延迟 ${delayTime}ms 以满足最小处理时间要求`);
await this.delay(delayTime);
}
this.successfulTasksInCurrentBatch++; // 增加成功任务计数
} catch (error) {
// **[健壮性改进]** 捕获到永久失败的错误。
// 原有逻辑会清空整个队列,导致后续任务丢失。
// 优化后的逻辑是:仅移除当前失败的任务,并记录错误,然后继续处理队列中的下一个任务。
// 任务永久失败
console.error(`[Queue] 🔥 任务永久失败: ${(error as Error).message}`);
const failedTask = this.queue.shift(); // 移除失败的任务
console.error(`[Queue] 失败的任务已被移除: ${JSON.stringify(failedTask)},将继续处理下一个任务。`);
this.failedTasksInCurrentBatch++; // 增加失败任务计数
} finally {
// 无论成功或失败,都增加已完成任务计数
this.completedTasksInCurrentBatch++;
// 即使任务失败,也需要满足最小处理时间要求
// 每次任务完成(或失败),都更新进度
this.reportBatchProgress();
// 检查是否所有任务都已处理完
if (this.queue.length === 0 && this.completedTasksInCurrentBatch === this.totalTasksInCurrentBatch) {
console.log('[Queue] 所有任务处理完毕!');
this.onAllTasksCompletedCallback?.(
this.totalTasksInCurrentBatch,
this.completedTasksInCurrentBatch,
this.successfulTasksInCurrentBatch,
this.failedTasksInCurrentBatch
);
// 重置批次计数器,为下一批次做准备
this.resetBatchCounters();
}
// 计算任务实际耗时,并根据需要延迟
const elapsedTime = Date.now() - this.taskStartTime;
if (elapsedTime < this.minProcessingTime) {
const delayTime = this.minProcessingTime - elapsedTime;
console.log(`[Queue] 失败任务处理耗时 ${elapsedTime}ms需要延迟 ${delayTime}ms 以满足最小处理时间要求`);
console.log(`[Queue] 任务处理耗时 ${elapsedTime}ms需要延迟 ${delayTime}ms 以满足最小处理时间要求`);
await this.delay(delayTime);
}
}
@ -92,6 +165,32 @@ export class ProcessDataTaskPool {
console.log('[Queue] 处理器已停止。');
}
/**
* 报告批次进度
*/
private reportBatchProgress(): void {
if (this.onBatchProgressUpdateCallback && this.totalTasksInCurrentBatch > 0) {
const progressPercentage = Math.floor((this.completedTasksInCurrentBatch / this.totalTasksInCurrentBatch) * 100);
this.onBatchProgressUpdateCallback(
this.totalTasksInCurrentBatch,
this.completedTasksInCurrentBatch,
this.successfulTasksInCurrentBatch,
this.failedTasksInCurrentBatch,
progressPercentage
);
}
}
/**
* 重置批次任务计数器
*/
private resetBatchCounters(): void {
this.totalTasksInCurrentBatch = 0;
this.completedTasksInCurrentBatch = 0;
this.successfulTasksInCurrentBatch = 0;
this.failedTasksInCurrentBatch = 0;
}
/**
* 延迟指定时间
* @param ms 延迟的毫秒数
@ -101,16 +200,12 @@ export class ProcessDataTaskPool {
}
private async processSingleTaskWithRetries(taskData: RegulatoryInterfaceParams): Promise<void> {
// 1 次初次尝试 + 5 次重试
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
const attemptNum = attempt + 1;
try {
const attemptType = attempt === 0 ? '初次尝试' : `重试 ${attempt}`;
console.log(`[Queue] 开始上传 (${attemptType}, 总共第 ${attemptNum} 次)`);
// **注意**: 这里传递的是 taskData 的引用,为了防止 worker 中意外修改原始数据,
// 最佳实践是在 worker 内部或传递前进行深拷贝。
// 但根据我们下面的修复worker 不再修改原始数据,所以这里是安全的。
const result: WR = await taskpool.execute(uploadWorkerTask, taskData);
dConsole.writeProcessData(ProcessDataEnumType.WuxiExam, JSON.stringify(result));
@ -120,7 +215,6 @@ export class ProcessDataTaskPool {
}
console.warn(`[Queue] ❌ 上传失败 (第 ${attemptNum} 次)。响应: ${result.message}`);
} catch (e) {
// **[健壮性改进]** 现在可以捕获从 Worker 抛出的更详细的异常信息
console.error(`[Queue] ❌ TaskPool 执行或网络错误 (第 ${attemptNum} 次): ${e}`);
}
@ -129,33 +223,22 @@ export class ProcessDataTaskPool {
}
}
// 如果循环结束,意味着所有尝试都失败了
throw new Error(`任务 ${JSON.stringify(taskData)} 在 ${this.maxRetries + 1} 次尝试后永久失败。`);
}
}
export const ProcessDataTaskPoolInstance = new ProcessDataTaskPool();
/**
* 这是将在 Worker 线程中执行的任务函数。
* 它负责执行单次的上传尝试。
* @param data 需要上传的单条数据项
* @returns 一个包含本次上传尝试结果的对象
*/
export async function uploadWorkerTask(data: RegulatoryInterfaceParams): Promise<WR> {
// 这两个变量似乎未在逻辑中使用,暂时保持原样
let singlePlay: boolean = false;
let isJGNew = false;
try {
const response = await sendProcessData(data, singlePlay, isJGNew);
return response;
} catch (err) {
// [健壮性改进] 捕获请求过程中的异常,并重新抛出。
// 这能让主线程的 taskpool.execute() promise 变为 rejected 状态,
// 从而被 processSingleTaskWithRetries 中的 try-catch 捕获,保留了详细的错误信息。
const error = err as Error;
console.error(`[Worker] 上传时发生异常: ${error.message}`);
throw error; // 重新抛出异常
throw error;
}
}
@ -167,7 +250,9 @@ async function sendProcessData(data: RegulatoryInterfaceParams, singlePlay: bool
// 调用新监管
}
data.drvexam = data.drvexam ?? {};
data.drvexam.zp = data.drvexam.zp === undefined ? undefined : encodeURIComponent(data.drvexam.zp);
if (data.drvexam.zp !== undefined && data.drvexam.zp !== null) {
data.drvexam.zp = encodeURIComponent(data.drvexam.zp);
}
const drvexamArr = Object.entries(data.drvexam)
.filter((item: [string, string]) => item[1] != undefined)
@ -176,7 +261,7 @@ async function sendProcessData(data: RegulatoryInterfaceParams, singlePlay: bool
return await Request<object>({
host: JGHOST,
url: '/dems_ws/services/TmriOutAccess?wsdl',
data: `<?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" > <SOAP-ENV:Body> <writeObjectOut xmlns="http://service.es.doron"> <xtlb>${data.xtlb}</xtlb> <jkxlh>${data.jkxlh}</jkxlh> <jkid>${data.jkid}</jkid> <UTF8XmlDoc> <![CDATA[ <?xm lversion="1.0 "encoding="GBK"?> <root> <drvexam> ${drvexamArr} </drvexam> </root> ]]> </UTF8XmlDoc> </writeObjectOut> </SOAP-ENV:Body> </SOAP-ENV:Envelope>`,
data: `<?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" > <SOAP-ENV:Body> <writeObjectOut xmlns="http://service.es.doron"> <xtlb>${data.xtlb}</xtlb> <jkxlh>${data.jkxlh}</jkxlh> <jkid>${data.jkid}</jkid> <UTF8XmlDoc> <![CDATA[ <?xm lversion="1.0 "encoding="GBK"?> <root> <drvexam> ${drvexamArr.join('')} </drvexam> </root> ]]> </UTF8XmlDoc> </writeObjectOut> </SOAP-ENV:Body> </SOAP-ENV:Envelope>`,
method: http.RequestMethod.POST,
xml: true
})