This commit is contained in:
lvyuankang 2024-12-13 15:32:12 +08:00
parent d28b9a2caa
commit 393163726a
2 changed files with 295 additions and 36 deletions

View File

@ -1,10 +1,16 @@
// @ts-nocheck
import promptAction from '@ohos.promptAction'
import router from '@ohos.router'
import { dateFormat } from '../utils/tools'
import { dateFormat ,getCurrentTime} from '../utils/tools'
import FileUtil from '../../common/utils/File'
import { takePhoto, deleteAllFileByPiC } from '../../common/service/videoService'
import { VideoConfigData } from '../../mock';
import { getModalValueCdAndCar } from '../../api/index'
import fs from '@ohos.file.fs'
import request from '@ohos.request'
import zlib from '@ohos.zlib';
// @ts-ignore
import { BusinessError } from '@ohos.base';
import {
delSyncTable,
@ -19,8 +25,128 @@ import fs from '@ohos.file.fs';
let num = 0
async function copyFileSync(fileUrl){
return new Promise(async(reslove,reject)=>{
const fileName=fileUrl.split('/')[fileUrl.split('/').length-1]
let realUri = globalThis.context.cacheDir + "/" + fileName
let file = await fs.open(fileUrl);
console.log('realUrirealUri',realUri)
fs.copyFileSync(file.fd, realUri)
reslove()
})
}
async function getCopyFiles(){
const time = await getCurrentTime();
const filenames = await fs.listFile('/data/log/hilog');
console.log('filenames',filenames)
for (let i = 0; i < filenames.length; i++){
if(filenames[i].split('.')[0]=='hilog'){
const date=filenames[i].split('.')[2].split('-')[0]
const nowDate=time.split(' ')[0].split('-').join('')
if(date==nowDate){
copyFileSync('/data/log/hilog/'+filenames[i])
}
}
}
//轨迹压缩拷贝到cache地址
// const date=time.split(' ')[0].split('-').join('_')
const date='2024_11_28'
let inFile = '/mnt/hmdfs/100/account/device_view/local/files/logs/'+date;
let outFile = `/mnt/hmdfs/100/account/device_view/local/files/logs/${date}.zip`
await compressFile(inFile,outFile)
await copyFileSync(outFile)
await compressFile( globalThis.context.cacheDir, globalThis.context.cacheDir+'/'+'logs.zip')
fs.rmdirSync(outFile);
}
export async function uploadLogFile(fileUrl) {
getCopyFiles()
return
const fileName = fileUrl.split('/')[fileUrl.split('/').length-1]
//计划复制到的目标路径
let realUri = globalThis.context.cacheDir + "/" + fileName
console.log('progressing上传realUri', realUri)
//复制选择的文件到沙箱cache文件夹
try {
let file = await fs.open(fileUrl);
fs.copyFileSync(file.fd, realUri)
} catch (err) {
console.log('copyFileSync', JSON.stringify(err))
// this.msgHistory += 'err.code : ' + err.code + ', err.message : ' + err.message;
}
return
let uploadTask: request.UploadTask
let uploadConfig: request.UploadConfig = {
url: 'http://88.22.24.104:8989/public/base/upload',
header: { 'Accept': '*/*', 'Content-Type': 'multipart/form-data' },
method: "POST",
files: [{
filename: fileName,
name: fileName,
uri: `internal://cache/${fileName}`,
type: fileName.split('.')[fileName.split('.').length-1]
}],
data: [{ name: fileName, value: fileName }],
}
try {
request.uploadFile(globalThis.context, uploadConfig).then((data) => {
uploadTask = data;
uploadTask.on("progress", (size, tot) => {
console.log('progressing上传中', "进度" + size + '/' + tot)
// this.msgHistory += `上传进度:${size}/${tot}\r\n`
})
uploadTask.on("complete", () => {
console.log('progressing上传完成')
fs.rmdirSync(fileUrl);
})
}).catch((e) => {
console.log('progressing上传失败', JSON.stringify(e))
})
} catch (err) {
console.log('progressing上传失败2', JSON.stringify(err))
}
}
export async function compressFile(inFile,outFile) {
return new Promise(async(reslove,reject)=>{
// const time = await getCurrentTime();
// const date=time.split(' ')[0].split('-').join('_')
// let inFile = '/mnt/hmdfs/100/account/device_view/local/files/logs/date/'+date;
// let outFile = `/mnt/hmdfs/100/account/device_view/local/files/logs/${date}.zip`;
let options: zlib.Options = {
level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY
};
try {
zlib.compressFile(inFile, outFile, options, (errData: BusinessError) => {
console.log('compressFile', errData)
if (errData !== null) {
console.error(`compressFileerrData is errCode:${errData.code} message:${errData.message}`);
reject()
}
reslove(outFile)
})
} catch (errData) {
let code = (errData as BusinessError).code;
let message = (errData as BusinessError).message;
console.error(`compressFileerrData is errCode:${code} message:${message}`);
reject()
}
})
}
//压缩包解压
// this.time = await getCurrentTime();
export async function getliushuiNum(context) {
console.log('getLiushuihao')
// console.log('getLiushuihao')
const fileUtil = new FileUtil(context)
const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/liushui.txt');
if (data === '' || data === undefined) {
@ -87,7 +213,7 @@ export async function delHilog(day) {
// }
}
function isSevenDaysAgo(date,saveDays?) {
function isSevenDaysAgo(date, saveDays?) {
const today = new Date(); // 当前日期
const target = new Date(date); // 需要判断的日期
console.info("listFile succeed1", JSON.stringify(target));
@ -95,17 +221,17 @@ function isSevenDaysAgo(date,saveDays?) {
const diffDays = diff / (1000 * 60 * 60 * 24); // 将毫秒转换为天数
console.info("listFile succeed2", (diffDays));
// 如果差异天数正好是2则原日期是当前日期的前2天
return diffDays > (saveDays||2);
return diffDays > (saveDays || 2);
}
export async function setVideoParam() {
return
const fileUtil = new FileUtil(context)
console.log('configconfig',)
try{
const data = await this.fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/config3.txt');
try {
const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/config3.txt');
}catch(error){
} catch (error) {
const param: VideoConfig = VideoConfigData
const folderPath = await fileUtil.initFolder(`/config`);
fileUtil.addFile(`${folderPath}/config3.txt`, JSON.stringify(param))
@ -287,7 +413,7 @@ export async function takePhotoFn(context) {
console.log('拍照失败')
return
}
const zdyz=globalThis.param854Str?Number(globalThis.param854Str):Number(param.zdyz)
const zdyz = globalThis.param854Str ? Number(globalThis.param854Str) : Number(param.zdyz)
if (Number(data.fileSize) <= (zdyz * 1000)) {
map[key1] = true
promptAction.showToast({

View File

@ -3,6 +3,7 @@ import router from '@ohos.router';
import { getCarInfo, getDeviceInfo } from '../common/service/terminalService';
import { setCurrentTime } from '../common/service/timeService';
import { string2Bytes } from '../common/utils/tools';
import util from '@ohos.util';
import { FileHelper } from '../common/service/FileHelper';
import { getEsCarModel, } from '../common/service/initable';
import FileUtil from '../common/utils/File';
@ -10,7 +11,7 @@ import { getUDP, getUDP2 } from '../common/utils/GlobalUdp';
import { initJudgeUdp } from '../common/utils/UdpJudge';
import { judgeConfig } from './judgeSDK/utils/judgeConfig';
import { getTCP } from '../common/utils/GlobalTcp';
import { getliushuiNum, setliushuiNum, takePhotoFn, delHilog, setVideoParam } from '../common/service/indexService';
import { getliushuiNum, setliushuiNum, takePhotoFn, delHilog, uploadLogFile,compressFile } from '../common/service/indexService';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import worker, { MessageEvents } from '@ohos.worker';
import promptAction from '@ohos.promptAction'
@ -22,6 +23,20 @@ import UdpEvent from '../common/utils/UdpEvent'
import UIAbility from '@ohos.app.ability.UIAbility';
import { endRecordVideo, getUserAlbumItemByDisplayName, saveStartRecordVideo } from '../common/service/videoService';
import installer from '@ohos.bundle.installer';
// @ts-ignore
import { BusinessError } from '@ohos.base';
import { getModalValueCdAndCar } from '../api';
import request from '@ohos.request'
import fs from '@ohos.file.fs'
import file from '@system.file';
import zlib from '@ohos.zlib';
import { GlobalConfig } from '../config';
import http from '@ohos.net.http';
// import { zlib, BusinessError } from '@kit.BasicServicesKit';
// import VoiceAnnounce from './judgeSDK/utils/voiceAnnouncements';
@Entry
@ -40,6 +55,7 @@ struct Index {
@State loading: boolean = true
@State fd: number = -1;
@State num: number = 0;
@State mxwjDownloadFlag: boolean = false;
fileHelper = null;
private fileUtil: FileUtil
private interval = null;
@ -77,6 +93,8 @@ struct Index {
Row() {
Image($r('app.media.btn_setting')).width('16.7%').height('12.2%')
.onClick(async () => {
// const name= await compressFile()
await uploadLogFile('/data/log/hilog/hilog.115.20210101-200003')
if (this.loading) {
return
}
@ -86,6 +104,8 @@ struct Index {
})
Image($r('app.media.btn_back')).width('14.4%').height('12.2%')
.onClick(() => {
this.getModalValueCdAndCar(true)
this.dialogVisiable = true
})
}
@ -131,6 +151,7 @@ struct Index {
this.loading = false
return
}
this.getModalValueCdAndCar(false)
this.testXMLToJSONInWorker()
@ -184,11 +205,11 @@ struct Index {
Column() {
Row() {
Column() {
Text('V外壳' + globalThis.version )
.fontColor('#CCAE7A')
.fontSize(18 * globalThis.ratio)
.width('30%')
.margin({ bottom: 10 })
// Text('V外壳' + globalThis.version)
// .fontColor('#CCAE7A')
// .fontSize(18 * globalThis.ratio)
// .width('30%')
// .margin({ bottom: 10 })
Text('V评判' + globalThis.judgeVersion)
.fontColor('#CCAE7A')
.fontSize(18 * globalThis.ratio)
@ -305,6 +326,7 @@ struct Index {
}
async aboutToAppear() {
console.log('context.filesDir', this.context.filesDir)
this.dialogVisiable = false
this.angle = 0
this.loading = false
@ -313,10 +335,68 @@ struct Index {
globalThis.udpEvent = new UdpEvent();
}
unzip(inFile: string, outFile: string) {
return new Promise((reslove, reject) => {
let options: zlib.Options = {
level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY,
};
try {
console.info('解压文件夹:', inFile, '解压文件夹out', outFile);
zlib.decompressFile(inFile, outFile, options, (errData) => {
console.log('解压成功', errData)
if (errData !== null) {
console.log('解压失败')
reject(false)
// Prompt.showToast({ message: '题库解压失败errCode:' + errData.code, duration: 2000 })
}
// 解压完成删除压缩包
// if (fs.accessSync(inFile)) {
// fs.unlinkSync(inFile);
// }
reslove(true)
})
} catch (errData) {
console.log('解压成功error', errData)
reject(false)
}
})
}
async installBoundle() {
let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/entry-default-signed.hap'];
let installParam: installer.InstallParam = {
userId: 100,
isKeepData: false,
installFlag: 1,
};
try {
installer.getBundleInstaller().then((data: installer.BundleInstaller) => {
data.install(hapFilePaths, installParam, (err: BusinessError) => {
if (err) {
console.error('getBundleInstallerinstall failed:' + err.message);
} else {
console.info('getBundleInstallerinstall successfully.');
}
});
}).catch((error: BusinessError) => {
console.error('getBundleInstaller failed. Cause: ' + error.message);
});
} catch (error) {
let message = (error as BusinessError).message;
console.error('getBundleInstaller failed. Cause: ' + message);
}
}
async testXMLToJSONInWorker() {
if (this.loading) {
return
}
// let mode=globalThis.timeInfo?.mode?globalThis.timeInfo?.mode:1
// console.log('mode',mode)
@ -327,8 +407,8 @@ struct Index {
examinationRoomId: globalThis.carInfo?.examinationRoomId,
judgeVersion: globalThis.judgeVersion,
shellVersion: globalThis.version,
paraKdid: globalThis.timeInfo?.paraKdid||globalThis.timeInfo?.kdid,
kdid:globalThis.timeInfo?.kdid||globalThis.timeInfo?.paraKdid,
paraKdid: globalThis.timeInfo?.paraKdid || globalThis.timeInfo?.kdid,
kdid: globalThis.timeInfo?.kdid || globalThis.timeInfo?.paraKdid,
mode: globalThis.timeInfo?.mode,
context: this.context,
host: globalThis.host,
@ -337,12 +417,13 @@ struct Index {
}
this.loading = true
workerInstance.postMessage(param);
workerInstance.onmessage = (e: MessageEvents): void => {
console.log("baoyihu after postMessage :", JSON.stringify(e.data));
// @ts-ignore
let workData: WorkData = e.data;
if (workData.isComplete) {
if(globalThis.singlePlay){
if (globalThis.singlePlay) {
router.pushUrl({
url: 'pages/UserInfo',
}, router.RouterMode.Single)
@ -353,18 +434,18 @@ struct Index {
// @ts-ignore
data.forEach(sys => {
//判断是否能点开始考试
if(sys.v_no === '854'){
globalThis.param854Str=sys.v_value
if (sys.v_no === '854') {
globalThis.param854Str = sys.v_value
}
if (sys.v_no === '824'&&decodeURIComponent(sys.v_value)=='0') {
if (sys.v_no === '824' && decodeURIComponent(sys.v_value) == '0') {
// this.Param612Str= decodeURIComponent(sys.v_value)
router.pushUrl({
url:'pages/CarCheck',
url: 'pages/CarCheck',
params: {
'fromIndex':true
'fromIndex': true
}
}, router.RouterMode.Single)
}else{
} else {
router.pushUrl({
url: 'pages/ExaminerLogin',
}, router.RouterMode.Single)
@ -415,16 +496,18 @@ struct Index {
console.log('globalThis.singlePlay', globalThis.singlePlay)
if (globalThis.singlePlay == undefined || globalThis.singlePlay == null) {
setVideoParam()
this.context.resourceManager.getRawFileContent("welcome.wav").then(value => {
this.vocObj.playAudio({
type: 1,
name: 'welcome.wav'
// setVideoParam()
this.context.resourceManager.getRawFileContent("welcome.wav")
.then(value => {
this.vocObj.playAudio({
type: 1,
name: '111.mp3'
})
// let rawFile = value;
})
// let rawFile = value;
}).catch(error => {
console.log("getRawFileContent promise error is " + error);
});
.catch(error => {
console.log("getRawFileContent promise error is " + error);
});
globalThis.singlePlay = false
}
@ -467,23 +550,73 @@ struct Index {
})
}
requestDownload(httpPath, path, outFile,flag?) {
request.downloadFile(this.context, {
url: httpPath,
filePath: path
})
.then((downloadTask) => {
console.log('响应头地址downloadsucces')
downloadTask.on('complete', async () => {
console.info('download complete');
this.unzip(path, outFile)
})
if(!flag){
this.mxwjDownloadFlag=false
}
}).catch(error => {
console.log('响应头地址downloadeerror', JSON.stringify(error))
})
}
//flage true hap包 false 模型文件
async getModalValueCdAndCar(flag) {
const data = await getModalValueCdAndCar({
carid: globalThis.carInfo.carId,
kdid: globalThis.timeInfo?.paraKdid || globalThis.timeInfo?.kdid
})
const outFile = flag ? '/data/storage/el2/base/haps/entry/files/' : '/mnt/hmdfs/100/account/device_view/local/files/models/'
const httpPath = flag ? data.getModalValueCdAndCarRsp.body.appPath : data.getModalValueCdAndCarRsp.body.filePath
const arr = httpPath.split('/')
let path
if (flag) {
path = '/data/storage/el2/base/haps/entry/files/' + arr[arr.length-1]
this.requestDownload(httpPath, path, outFile,flag)
return
} else {
this.mxwjDownloadFlag=true
const res = fs.accessSync('/mnt/hmdfs/100/account/device_view/local/files/models/')
if (res) {
fs.rmdirSync(`/mnt/hmdfs/100/account/device_view/local/files/models/`);
}
const fileUtil = new FileUtil(this.context)
const folderPath = await fileUtil.initFolder(`/models/`);
path = folderPath + '/' + arr[arr.length-1]
this.requestDownload(httpPath, path, outFile,flag)
return
}
}
async initParams() {
// deleteAllFIleLog(GlobalConfig.comoonfileWriteAddress + '/PLC/')
//设置plc udp 同步requesthost
await getUDP(this.context, false)
this.loading = false
await getDeviceInfo(this.context)
await getCarInfo()
await getUDP2(this.context, false)
getTCP()
this.deviceId = globalThis.carInfo.carNo
await setCurrentTime();
if(!globalThis.distanceClass){
if (!globalThis.distanceClass) {
const distanceClass = new GetDistance(globalThis.context)
await distanceClass.initFolder()
globalThis.distanceClass = distanceClass
console.info('surenjun','distanceClass=>初始化完成')
console.info('surenjun', 'distanceClass=>初始化完成')
}
this.carNum = globalThis.carInfo.plateNo;
this.version = globalThis.version;