代码优化

This commit is contained in:
lixiao 2025-03-25 10:00:26 +08:00
parent d35a770c5a
commit 4fe0bc1361
11 changed files with 175 additions and 187 deletions

View File

@ -5,9 +5,9 @@
"name": "default",
"material": {
"certpath": "C:\\Users\\93218\\.ohos\\config\\openharmony\\auto_ohos_default_subject-two_com.oh.dts.cer",
"storePassword": "0000001B70DEAAC59CE48370ACDCBC340EC0C7617A8B95FA534141A29AC8F9AFE528874A2A8ADAA079D26F",
"storePassword": "0000001BE413F804F795E0CC5A4A0B989C4E25CFDE3A490ECD2436EB6420FE3E32A7E2A618CDD7EFE107B4",
"keyAlias": "debugKey",
"keyPassword": "0000001B50E66320DF9600EA16E69B46A1A500D13C7F01A10918A4D81185C9DD620698CDC794F58C03546E",
"keyPassword": "0000001B851FA9FF8A74DB639E4377C4BE9AA21ACFA27C4A2A39651CFFA5B4EF1A536194D666331204C740",
"profile": "C:\\Users\\93218\\.ohos\\config\\openharmony\\auto_ohos_default_subject-two_com.oh.dts.p7b",
"signAlg": "SHA256withECDSA",
"storeFile": "C:\\Users\\93218\\.ohos\\config\\openharmony\\auto_ohos_default_subject-two_com.oh.dts.p12"

View File

@ -31,7 +31,7 @@ export async function faceCompare(params) {
export async function getExaminationStudentInfo(params) {
return tempRequest({
return request({
url: '/der2/services/exam/getExaminationStudentInfo.ws',
data: params,
method: 'post',

View File

@ -7,124 +7,15 @@ import tempRequest from './tempRequest';
export default async function request<T>(req: any): Promise<T> {
return tempRequest(req)
return new Promise((resolve, reject) => {
let {url,params = {},data = {},xml,method = 'get',host,isNewCenter = false, timeout} = req;
try {
const options = {
method: http.RequestMethod[method.toUpperCase()],
header: {
'Content-Type': xml ? 'text/xml' : 'application/json'
},
extraData: xml ? data : JSON.stringify(data),
}
let paramsStr = Reflect.ownKeys(params).reduce((p: string, n: string) => (`${p}${n}=${params[n]}&`), '?') || '';
paramsStr = paramsStr.toString();
paramsStr = paramsStr.substring(0, paramsStr.length - 1)
let baseUrl = host ? host : globalThis.host
console.log('响应头地址1' + baseUrl, url, options.extraData.length)
tcpUtil.request(`${baseUrl}${url}${paramsStr}`, {
method: options.method,
data: xml ? data : JSON.stringify(data),
type: xml ? 1 : 0,
contentType: xml ? 'text/xml' : 'application/json',
timeout: timeout || 90000
}, (data) => {
try {
console.log(JSON.stringify(data))
const result = JSON.parse(JSON.stringify(data))
console.log('响应头地址' + JSON.stringify(result))
let res: any = xml ? xmlToJson(result, url) : result;
console.log('响应头地址 xml 后 res' + JSON.stringify(res))
console.log('响应头地址 xml 后 res 类型', typeof res)
let resObj = null;
if (typeof res === "string") {
res = JSON.parse(res)
}
//处理中心服务code
if (res.Envelope) {
const msgXml = res.Envelope.Body.writeObjectOutResponse.return;
const dd = handleCenterCode(msgXml, isNewCenter);
// @ts-ignore
resolve(dd)
return
}
if (!xml) {
if (res.head.resultCode === '0') {
resolve(res)
return
} else {
const resultMessage = res?.body?.resultMessage || res?.head?.resultMessage
prompt.showToast({
message: decodeURIComponent(resultMessage),
duration: 3000
});
reject(false)
}
}
for (let i in res) {
resObj = res[i].head
}
console.info('res in request' + url + JSON.stringify(resObj))
if (resObj.resultCode === '0') {
resolve(res)
return
} else {
Prompt.showToast({
message: decodeURIComponent(resObj.resultMessage),
duration: 3000
});
reject(res)
}
} catch (e) {
reject(e)
console.log("http parse error: ", JSON.stringify(e))
}
}, (error) => {
console.log("req timeout", JSON.stringify(error))
console.log("req timeout url", url)
if (!error || !(error?.message)) {
reject({
code: -1
})
}
const code = error?.code;
Prompt.showToast({
message: error?.message,
duration: 5000
});
switch (code) {
//断网
case 2300007:
reject({
code: 2300007
})
break;
// 超时
case 2300028:
reject({
code: 2300028
})
break;
default:
reject(error)
}
Prompt.showToast({
message: JSON.stringify(error),
duration: 3000
});
})
} catch (e) {
console.info('test-error' + url + ' error:resp: ' + JSON.stringify(e))
}
tempRequest(req).then(res => {
console.log("[http request] success url: ", req?.url)
resolve(res as T)
}).catch(err => {
console.log("[http request] error: ", JSON.stringify(err), "url: ", req?.url)
reject(err)
})
})
}

View File

@ -0,0 +1,59 @@
import hilog from '@ohos.hilog';
import file from '@ohos.file.fs'
export class CpuUsageMonitor {
private static readonly TAG: string = 'CpuUsageMonitor';
// 读取/proc/stat文件的第一行获取CPU的总时间信息
private static getCpuUsage(): number[] {
let cpuTimes: number[] = [];
try {
let result = file.openSync('/proc/stat', file.OpenMode.READ_ONLY);
let buffer = new ArrayBuffer(1024);
let len = file.readSync(result.fd, buffer, { offset: 0 });
let content = String.fromCharCode.apply(null, new Uint8Array(buffer, 0, len));
file.closeSync(result.fd);
let lines = content.split('\n');
if (lines.length > 0 && lines[0].startsWith('cpu ')) {
let parts = lines[0].split(/\s+/);
for (let i = 1; i <= 7; i++) {
cpuTimes.push(parseInt(parts[i]));
}
}
} catch (err) {
hilog.error(0x0000, this.TAG, `Failed to read /proc/stat: ${err.message}`);
}
return cpuTimes;
}
// 计算CPU使用率
private static calculateCpuUsage(prevCpuTimes: number[], currCpuTimes: number[]): number {
let prevIdle = prevCpuTimes[3] + prevCpuTimes[4]; // idle + iowait
let currIdle = currCpuTimes[3] + currCpuTimes[4]; // idle + iowait
let prevTotal = prevCpuTimes.reduce((a, b) => a + b, 0);
let currTotal = currCpuTimes.reduce((a, b) => a + b, 0);
let totalDiff = currTotal - prevTotal;
let idleDiff = currIdle - prevIdle;
if (totalDiff === 0) {
return 0;
}
return 100 * (totalDiff - idleDiff) / totalDiff;
}
public static printCpuUsage(): void {
setInterval(() => {
let prevCpuTimes = this.getCpuUsage();
setTimeout(() => {
let currCpuTimes = this.getCpuUsage();
let cpuUsage = this.calculateCpuUsage(prevCpuTimes, currCpuTimes);
hilog.info(0x0000, this.TAG, `Current CPU Usage: ${cpuUsage.toFixed(2)}%`);
}, 1000); // 等待1秒
}, 1000)
}
}

View File

@ -8,6 +8,7 @@ import { GlobalConfig } from '../config/global'
import { tcpUtil } from '../common/utils/TcpRequest';
import DB from '../common/database/DbSql';
import { initTable } from '../common/service/initable';
import { CpuUsageMonitor } from '../common/utils/usage';
export default class EntryAbility extends UIAbility {
async onCreate(want, launchParam) {
@ -35,6 +36,7 @@ export default class EntryAbility extends UIAbility {
// this.context
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
CpuUsageMonitor.printCpuUsage();
await tcpUtil.init()
Logger.init()
@ -72,8 +74,8 @@ export default class EntryAbility extends UIAbility {
const windowClass = await windowStage.getMainWindow();
globalThis.windowClass = windowClass
// await windowClass.setWindowLayoutFullScreen(true)
// await windowClass.setWindowSystemBarEnable([]) //全屏
await windowClass.setWindowSystemBarEnable(['navigation'])
await windowClass.setWindowSystemBarEnable([]) //全屏
// await windowClass.setWindowSystemBarEnable(['navigation'])
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {

View File

@ -44,6 +44,8 @@ struct Index {
}
async aboutToAppear() {
let currentParams: any = router.getParams();
this.mode = Number(currentParams.mode)
globalThis.windowClass.setWindowSystemBarEnable([])
const time = await getCurrentTime()
@ -60,7 +62,9 @@ struct Index {
//初始化数据库表
await this.initDb()
//断点续考
await this.goDdxkItems()
if(this.mode == 2) {
await this.goDdxkItems()
}
//初始化评判
const judge = await this.initJudge();
this.judge = judge
@ -250,8 +254,9 @@ struct Index {
let currentParams: any = router.getParams();
const {carName,carType,examSubject} = this;
this.mode = Number(currentParams.mode)
this.totalScore = Number(currentParams.score) || this.totalScore
if(this.mode === 2) {
this.totalScore = Number(currentParams.score) || this.totalScore
}
//小车车型列表
if (globalThis.singlePlay) {
this.wayno = currentParams.wayno || 1;
@ -287,6 +292,7 @@ struct Index {
//根据车型获取应行驶里程数
if (no1 == 3 && no3 == 15 && Number(carNo) == no2) {
let mileage = (decodeURI(systemParm.txt1) || '').split('^')
console.log("lixiao",decodeURI(systemParm.txt1))
if (this.mode === 1) {
this.examMileage = mileage[1]
} else if (this.mode === 2) {
@ -445,12 +451,13 @@ struct Index {
// 夜考扣分
async goDdxkItems() {
let currentParams: any = router.getParams();
if(!currentParams?.examItems) {
return
}
const examItems: string = currentParams?.examItems + "";
console.log("lixiao ddxkKfArr", JSON.stringify(examItems))
const ddxkKfArr = examItems?.split(",").filter(item => item)
if(ddxkKfArr.length === 0) {
return
}
console.log("lixiao ddxkKfArr", JSON.stringify(ddxkKfArr))
console.log("lixiao ddxkKfArr", JSON.stringify(this.manualMarkRules))
console.log("lixiao ddxkKfArr", JSON.stringify(this.markRuleListObj))

View File

@ -91,13 +91,14 @@ export default struct Index {
goJudge(wayno) {
let currentParams: any = router.getParams() || {};
const {sczb,kfdm} = currentParams;
const {sczb,kfdm, mode} = currentParams;
router.replaceUrl({
url: 'pages/Judge',
params:{
sczb,
kfdm,
wayno,
mode
}
}, router.RouterMode.Single);

View File

@ -105,7 +105,7 @@ struct UserInfo {
}
}
//开始考试准备
prePareExam = async () => {
prePareExam = async (mode?: number) => {
if (this.ksksLimit) {
return
}
@ -119,18 +119,17 @@ struct UserInfo {
this.ksksLimit = true
if (globalThis.singlePlay) {
const {examSubject} = globalThis.carInfo;
this.currentUser.id = '0'
await upDateTableByArray('USER', [this.currentUser])
router.pushUrl({
url: examSubject == 3 ? 'pages/Roads' : 'pages/Judge',
url: 'pages/Roads',
params: {
sczb: Number(this.isBoardPrePareSetPopupOpen),
kfdm: this.sczbkf,
mode
}
}, router.RouterMode.Single);
this.ksksLimit = false
this.stopDeviceById()
return
}
@ -323,7 +322,6 @@ struct UserInfo {
params: {
sczb: Number(this.isBoardPrePareSetPopupOpen),
kfdm: this.sczbkf,
}
}, router.RouterMode.Single);
return
@ -439,26 +437,37 @@ struct UserInfo {
this.mode === 5
return
}
const result = await getSyncData('ES_CARINFO')
const carInfo = result[0] || {};
let carName = decodeURI(carInfo?.carclass)
let carNo
let nightTime = ''
const syssetParams = await getSyncData('MA_SYSSET');
const systemParams: SYSTEMPARMARR[] = (await getSyncData('MA_SYSTEMPARM')) as SYSTEMPARMARR[]
//@ts-ignore
syssetParams.forEach((sys) => {
if (sys.v_no === 19) {
nightTime = sys.v_value
if (sys.v_no == 19) {
nightTime = decodeURIComponent(sys.v_value)
}
})
systemParams.forEach(item => {
if (item.NO3 === 20) {
nightTime = item.TXT1
if (item.no1 == 3 && item.no3 == 1 && decodeURIComponent(item.txt1) == carName) {
carNo = item.no2 + ''
}
if (item.no1 == 3 && item.no3 == 20 && carNo == item.no2) {
console.log("lixiao", JSON.stringify(item), carNo, nightTime)
nightTime = decodeURIComponent(item.txt1) || nightTime
}
// if (carNo) {
// console.log("lixiao", JSON.stringify(item), carNo, nightTime)
// }
})
let now = new Date(await systemDateTime.getCurrentTime())
let hour = now.getHours()
let minute = now.getMinutes()
let t_hour = Number(nightTime.split(":")[0])
let t_minute = Number(nightTime.split(":")[1])
console.log("lixiao nightTime", nightTime)
console.log("lixiao nightTime", hour, minute, t_hour, t_minute)
if (kStringArr.length === 0) {
if (hour > t_hour || (hour === t_hour && minute >= t_minute)) {
this.mode = 2
@ -693,6 +702,7 @@ struct UserInfo {
this.errorDialog.open()
this.updateTimeLimit = true
const param = `<getExaminationStudentInfoReq><head><checkCode>${Md5.Instance.get_md5(globalThis.carInfo.carId + globalThis.carInfo.examinationRoomId + globalThis.username)}</checkCode></head><body><carId>${globalThis.carInfo.carId}</carId><examinationRoomId>${globalThis.carInfo.examinationRoomId}</examinationRoomId><examinerName>${globalThis.username}</examinerName><sfzmhm></sfzmhm></body></getExaminationStudentInfoReq>`
console.log("lixiao", param)
try {
getExaminationStudentInfo(param).then(async (res) => {
console.log("lixiao student", JSON.stringify(res))
@ -916,7 +926,7 @@ struct UserInfo {
let kStringArr = decodeURIComponent(keystr || '').split(",").filter(item => item)
console.log("lixiao kStringArr", JSON.stringify(kStringArr))
await this.getExamMode(kStringArr)
console.log("lixiao model", this.mode,JSON.stringify(examItems))
console.log("lixiao model", this.mode)
let score = Number(this.currentUser.jdxx?.split("^")[0])
let kfxm = this.currentUser.jdxx?.split("^")[1]
let length = Number(this.currentUser.jdxx?.split("^")[2])
@ -929,6 +939,15 @@ struct UserInfo {
this.stepFlag = false
this.ksksLimit = false
return
} else if(this.mode === 1 && this.currentUser.jdxx) {
promptAction.showToast({
message: "当前尚未进入夜考时间,无法开始夜考!"
})
this.updateTimeLimit = false
this.stopDeviceById()
this.stepFlag = false
this.ksksLimit = false
return
}
router.pushUrl({
url: 'pages/Judge',
@ -1245,27 +1264,36 @@ struct UserInfo {
// .commStyle()
imageBtn({ btnWidth: 220 * this.ratio, btnHeight: 69 * this.ratio, imgSrc: $r('app.media.gx_btn') })
.margin({ bottom: 12 * this.ratio })
.onClick(() => {
// this.avPlayer.playAudio(['button_media.wav'])
if (this.isExamStart && !globalThis.singlePlay) {
return
.onClick(async () => {
if (globalThis.singlePlay) {
await this.prePareExam(3)
} else {
// this.avPlayer.playAudio(['button_media.wav'])
if (this.isExamStart && !globalThis.singlePlay) {
return
}
this.faceCompareSucess = 0
this.numCount = 0
this.getExaminationStudentInfoFn()
}
this.faceCompareSucess = 0
this.numCount = 0
this.getExaminationStudentInfoFn()
})
// Image($r('app.media.qk_btn'))
// .commStyle()
imageBtn({ btnWidth: 220 * this.ratio, btnHeight: 69 * this.ratio, imgSrc: $r('app.media.qk_btn') })
.margin({ bottom: 12 * this.ratio })
.onClick(() => {
// this.avPlayer.playAudio(['button_media.wav'])
// 已开始考试不能缺考 已考过一次学员不能缺考 车上不能缺考
if (this.ksksLimit || (this.systemParam.Param352Str == '1' && this.currentUser.kssycs == '1') || this.systemParam.Param770Str == '1') {
return
.onClick(async () => {
if (globalThis.singlePlay) {
await this.prePareExam(2)
} else {
// this.avPlayer.playAudio(['button_media.wav'])
// 已开始考试不能缺考 已考过一次学员不能缺考 车上不能缺考
if (this.ksksLimit || (this.systemParam.Param352Str == '1' && this.currentUser.kssycs == '1') || this.systemParam.Param770Str == '1') {
return
}
this.ksksLimit = true
this.qkFlag = true
}
this.ksksLimit = true
this.qkFlag = true
})
if (this.isBoardPrePareSetPopupOpen && (this.isSecondBoardPrePareSetPopupOpen && this.currentUser.kssycs == '2') && !this.isFirstBoardPrePareSetPopupBtnShow) {
@ -1274,10 +1302,14 @@ struct UserInfo {
imageBtn({ btnWidth: 220 * this.ratio, btnHeight: 69 * this.ratio, imgSrc: $r('app.media.sczb_btn') })
.margin({ bottom: 12 * this.ratio })
.onClick(async () => {
if (this.systemParam.Param612Str == '1') {
return
if (globalThis.singlePlay) {
} else {
if (this.systemParam.Param612Str == '1') {
return
}
await this.prePareSCZB()
}
await this.prePareSCZB()
})
} else {
// Image($r('app.media.ksks_btn'))
@ -1285,10 +1317,14 @@ struct UserInfo {
imageBtn({ btnWidth: 220 * this.ratio, btnHeight: 69 * this.ratio, imgSrc: $r('app.media.ksks_btn') })
.margin({ bottom: 12 * this.ratio })
.onClick(async () => {
if (this.systemParam.Param612Str == '1') {
return
if (globalThis.singlePlay) {
await this.prePareExam(1)
} else {
if (this.systemParam.Param612Str == '1') {
return
}
await this.prePareExam()
}
await this.prePareExam()
})
}
}

View File

@ -487,7 +487,7 @@ export default class Judge {
const msgStr = strArr[num];
if (msgStr == '') {
console.info(judgeTag, '模拟数据考试结束')
globalThis.windowClass.setWindowSystemBarEnable(['navigation'])
// globalThis.windowClass.setWindowSystemBarEnable(['navigation'])
clearInterval(judgeTimer)
this.checkExamIsEnd(true)
return
@ -678,9 +678,9 @@ export default class Judge {
this.trajectoryPath = trajectoryPath;
this.isExam = !this.judgeUI.singlePlay;
const {projectsCenterObj,examSubject} = judgeUI;
const {projectsCenterObj} = judgeUI;
(examSubject == 2 ? testKm2Items : testKm3Items).forEach(item => {
testKm3Items.forEach(item => {
const projectCenterObj = projectsCenterObj[item.code]
this.testKmItems[item.code] = item;
//考试项目存在
@ -707,24 +707,15 @@ export default class Judge {
const { examSubject,plateNo,carId } = carInfo;
const judgeUI = this.judgeUI
const {projectsObj,itemInfoObj,markRuleListObj,carType,carName,systemparmArr,carinfoArr} = judgeUI
const examType = examSubject == 2 ? 'km2' : 'km3'
const examType = 'km3'
let allitems = [];
if (examSubject == 2) {
allitems = Reflect.ownKeys(itemInfoObj).map(cdsbKey => {
const cdsb = itemInfoObj[cdsbKey];
const {xmdm,xmxh,modelKey} = cdsb
return {
xmdm, xmxh, model: getModelData(`${examType}/${modelKey}.txt`)
}
})
}
//获取版本号
const sdkver = await examJudgeVersion();
const initInfo = {
sdkver,
appver: globalThis.version,
kskm: examSubject * 1,
kskm: 3,
kchp: plateNo,
kchm: carId * 1,
kscx: carType,
@ -761,7 +752,11 @@ export default class Judge {
const {isExam} = this;
const judgeUI = this.judgeUI
const {projects,carType,kssycs,isDdxk,ddxkTime,projectsCenterObj,ddxkKsxmArr,ddxkKfArr,passingScore} = judgeUI;
console.log("lixiao projects", JSON.stringify(projects.map(item => item.name)))
let sfyk = 0
if (judgeUI.mode === 2) {
sfyk = 1
}
console.log("lixiao projects", judgeUI.mode, sfyk)
const beginInfo = {
kgid: '012',
kgxm: decodeURI(examinerName || ''),
@ -777,8 +772,7 @@ export default class Judge {
ksyy: '',
kscx: carType,
kkcs: Number(kssycs) || 2,
// sfyk: this.judgeUI.mode === 2 ? 1 : 0,
sfyk: 1,
sfyk,
ykkkcs: 1,
wayno: judgeUI.wayno * 1,
czlx: 0,
@ -807,13 +801,12 @@ export default class Judge {
sczb: (sczb === undefined || sczb == 0) ? 0 : 1,
sczbkf: kfdm,
// 大车是否模拟灯光参数
dmndg: this.judgeUI.mode === 3 || this.judgeUI.mode === 5,
// dmndg: this.judgeUI.mode === 3,
dmndg: judgeUI.mode === 3 || judgeUI.mode === 5,
// 是否满分学习
mfxx: this.judgeUI.mode === 5,
mfxx: judgeUI.mode === 5,
// TODO 满分学习是否扣分参数
mfxxn: this.judgeUI.mfxxn,
zeng: this.judgeUI.mode === 3 || this.judgeUI.mode === 4
mfxxn: judgeUI.mfxxn,
zeng: judgeUI.mode === 3 || judgeUI.mode === 4
}
console.info(judgeTag, '5.获取开始考试数据完成')
return beginInfo
@ -1090,7 +1083,7 @@ export default class Judge {
console.info('surenjun', '扣分开始')
//扣分时实时播报语音0-否+1-是)
const currentKf = kf[kfLen -1];
if (judgeConfig.kfVoiceOpen || (examSubject == 2 && judgeConfigObj['618'] == '1') || (examSubject == 3 && judgeConfigObj['418'] == '1')) {
if (judgeConfig.kfVoiceOpen || (examSubject == 3 && judgeConfigObj['418'] == '1')) {
avPlayer.playAudio([`voice/${currentKf.markcatalog}.mp3`, `voice/mark_${Math.abs(currentKf.score)}.mp3`])
}
const isStart = await checkProjectIsStart(currentKf.xmdm, 2, currentKf);
@ -1461,10 +1454,8 @@ export default class Judge {
const { examSubject,plateNo,ksyh } = carInfo;
const {
judgeUI,
isExam,
serialIndex,
tempData,
xmmcCode,
xmxh,
xmmcSingleCode,
xmdm,
@ -1495,7 +1486,7 @@ export default class Judge {
const sbxh = getSbxh(xmdm, xmxh)
const {carzt,dcjl,qjjl,dxjl,bxjl} = performInfo || {};
const asclshArr = stringToASC(
fillZero((singlePlay ? (examSubject == 2 ? '0000000000000' : '1111111111111') : lsh) || 0, 13)
fillZero((singlePlay ? '1111111111111' : lsh) || 0, 13)
);
//13不足要补0
const ascksyhArr = stringToASC(fillZero(ksyh || 0, 13))

View File

@ -5,7 +5,8 @@ export const judgeConfig = {
//是否开启拍照
isPhotoOpen: true,
//扣分语音是否强制开启
kfVoiceOpen: false,
// kfVoiceOpen: false,
kfVoiceOpen: true,
//忽略的考试项目
ignoreProjects:[],
// 是否忽略考试前熄火、车门检查

View File

@ -17,7 +17,7 @@
"abilities": [
{
"name": "EntryAbility",
"srcEntrance": "./ets/entryability/EntryAbility.ts",
"srcEntrance": "./ets/entryability/EntryAbility.ets",
"description": "$string:EntryAbility_desc",
"icon": "$media:logo_app",
"label": "$string:EntryAbility_label",