From 092cab3032b8f7aaaeee6063a77e23904386a577 Mon Sep 17 00:00:00 2001 From: lixiao <932184220@qq.com> Date: Wed, 18 Dec 2024 09:14:10 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A5=E5=BF=97=E6=89=93=E5=8C=85=E4=B8=8A?= =?UTF-8?q?=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/ets/common/service/indexService.ts | 159 ++++---- entry/src/main/ets/common/utils/GlobalUdp.ts | 125 +++--- entry/src/main/ets/common/utils/request.ts | 384 +++++++++--------- entry/src/main/ets/pages/Index.ets | 77 ++-- 4 files changed, 377 insertions(+), 368 deletions(-) diff --git a/entry/src/main/ets/common/service/indexService.ts b/entry/src/main/ets/common/service/indexService.ts index 7cec71bc..e10510b4 100644 --- a/entry/src/main/ets/common/service/indexService.ts +++ b/entry/src/main/ets/common/service/indexService.ts @@ -1,16 +1,13 @@ // @ts-nocheck import promptAction from '@ohos.promptAction' import router from '@ohos.router' -import { dateFormat ,getCurrentTime} from '../utils/tools' +import { dateFormat, getCurrentTime } from '../utils/tools' import FileUtil from '../../common/utils/File' -import { takePhoto, deleteAllFileByPiC } from '../../common/service/videoService' +import { takePhoto } 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, @@ -25,57 +22,96 @@ 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 copyFileSync(fileUrl) { + return new Promise(async (resolve, reject) => { + try { + const fileName = fileUrl.split('/')[fileUrl.split('/').length-1] + let realUri = globalThis.context.cacheDir + "/" + fileName + let file = await fs.open(fileUrl); + fs.copyFileSync(file.fd, realUri) + resolve() + } catch (err) { + reject(err) + } }) } -async function getCopyFiles(){ + +// 打包当天日志文件 +async function compressCurrentLogs() { const time = await getCurrentTime(); + const nowDate = time.split(' ')[0].split('-').join('') 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]) + for (let i = 0; i < filenames.length; i++) { + if (filenames[i].split('.')[0] == 'hilog') { + const date = filenames[i].split('.')[2].split('-')[0] + if (date == nowDate) { + fs.copyFileSync('/data/log/hilog/' + filenames[i], globalThis.context.cacheDir + '/temp/' + 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 + +// 将要上传的文件拷贝到缓存目录并压缩 +async function getCopyFiles() { + if (!fs.accessSync(globalThis.context.cacheDir + '/temp')) { + fs.mkdirSync(globalThis.context.cacheDir + '/temp') + } + await compressCurrentLogs() + const date = '2024_11_28' + let inFile = '/mnt/hmdfs/100/account/device_view/local/files/logs/' + date; + let outFile = globalThis.context.cacheDir + '/temp/' + date + fs.copyFileSync(inFile, outFile) + await compressFile(globalThis.context.cacheDir + '/temp/', globalThis.context.cacheDir + '/' + 'logs.zip') + fs.rmdirSync(globalThis.context.cacheDir + '/temp'); +} + +export async function uploadLogFile() { + // test('/data/log/hilog/hilog.115.20210101-200003') + // return + let filename = 'test.zip' + await getCopyFiles() + // return + let uploadTask: request.UploadTask + + let stat = fs.statSync(globalThis.context.cacheDir + '/' + filename) + console.log(stat.size) + let uploadConfig: request.UploadConfig = { + header: { 'Accept': '*/*', 'Content-Type': 'multipart/form-data' }, + url: `http://88.22.20.117:8082/der2/services/upload??fileName=${filename}`, + files: [{ filename, name: filename, uri: `internal://cache/${filename}`, type: "zip" }], + 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) + }) + uploadTask.on('complete', () => { + console.log('progressing上传完成') + // fs.rmdirSync(globalThis.context.cacheDir + '/' + 'logs.zip'); + }) + uploadTask.on("headerReceive", header => { + console.log(JSON.stringify(header)) + }) + }).catch((e) => { + console.log('progressing上传失败', e) + }) + } catch (err) { + console.log('progressing上传失败2', err) + } +} + +async function test(fileUrl) { 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) + fs.copyFileSync(fileUrl, 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', @@ -94,7 +130,6 @@ async function getCopyFiles(){ uploadTask = data; uploadTask.on("progress", (size, tot) => { console.log('progressing上传中', "进度" + size + '/' + tot) - // this.msgHistory += `上传进度:${size}/${tot}\r\n` }) uploadTask.on("complete", () => { @@ -108,41 +143,16 @@ async function getCopyFiles(){ } 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 compressFile(inFile, outFile) { + let options: zlib.Options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY + }; + return zlib.compressFile(inFile, outFile, options) +} export async function getliushuiNum(context) { @@ -347,7 +357,6 @@ export async function getSingleCenterTable(param) { } - let interval export async function takePhotoFn(context) { diff --git a/entry/src/main/ets/common/utils/GlobalUdp.ts b/entry/src/main/ets/common/utils/GlobalUdp.ts index f410b6b9..a3efbb7f 100644 --- a/entry/src/main/ets/common/utils/GlobalUdp.ts +++ b/entry/src/main/ets/common/utils/GlobalUdp.ts @@ -1,28 +1,28 @@ //import UdpClient from './UdpClient'; import UdpClientByCenter from './UdpClientByCenter'; import { getSyncData } from '../service/initable' -import { getChuankouFn } from '../../common/service/indexService' +import { getChuankouFn, uploadLogFile } from '../../common/service/indexService' import FileUtil from '../../common/utils/File' import { GlobalConfig } from '../../config/index' -import {Array2Byte,fillZero,string2Bytes}from './tools' +import { Array2Byte, fillZero, string2Bytes } from './tools' import emitter from '@ohos.events.emitter'; export async function sendMsg(val) { // globalThis.udpClient1&&globalThis.udpClient1.sendMsg(val) } -export async function getUDP(context,errorFlag?) { - return new Promise(async (reslove,reject)=>{ +export async function getUDP(context, errorFlag?) { + return new Promise(async (reslove, reject) => { const fileUtil = new FileUtil(context) const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); - console.log('ttttt',data) + console.log('ttttt', data) if (data === '' || data === undefined) { console.log(` getUDP has no IPConfigTable `); globalThis.udpClient = {} globalThis.host = '' reslove('') } else { - const result=JSON.parse(data) + const result = JSON.parse(data) console.log(` getUDP has IPConfigTable `); if (globalThis.udpClient && globalThis.udpClient.closeUdp) { console.log(` getUDP has udclent close and rebind `); @@ -31,11 +31,11 @@ export async function getUDP(context,errorFlag?) { globalThis.udpClient.rebindUdp(result.udplocalIp, result.udplocalIpPort, result.udpOppositeIp, result.udpOppositeIpPort) globalThis.udpClient.sendMsg('111', null) globalThis.host = `http://${result.centerIp}:${result.centerPort}` - globalThis.udpClient.onError_Callback(()=>{ + globalThis.udpClient.onError_Callback(() => { console.log('getUDPgetUDPgetUDP') - getUDP(context,true) - if(errorFlag&&globalThis.udpClient&&globalThis.udpClient.onMessage_1){ - globalThis.udpClient.onMessage_1=globalThis.udpClient.onMessage_1 + getUDP(context, true) + if (errorFlag && globalThis.udpClient && globalThis.udpClient.onMessage_1) { + globalThis.udpClient.onMessage_1 = globalThis.udpClient.onMessage_1 } }) reslove(`http://${result.centerIp}:${result.centerPort}`) @@ -48,21 +48,21 @@ export async function getUDP(context,errorFlag?) { else { // 未绑定 console.log(` getUDP has no udclent and bind `); - console.log('ttttttdata',JSON.stringify(result)) + console.log('ttttttdata', JSON.stringify(result)) const udpClient: UdpClientByCenter = new UdpClientByCenter(result.udplocalIp, result.udplocalIpPort, result.udpOppositeIp, result.udpOppositeIpPort) udpClient.bindUdp() udpClient.sendMsg('111') globalThis.host = `http://${result.centerIp}:${result.centerPort}` globalThis.udpClient = udpClient - globalThis.udpClient.onMessage_1(()=>{ + globalThis.udpClient.onMessage_1(() => { console.log('getUDPonMessage_1msgmsgByGloalUdp') }) - globalThis.udpClient.onError_Callback(()=>{ - getUDP(context,true) - if(errorFlag&&globalThis.udpClient&&globalThis.udpClient.onMessage_1){ - globalThis.udpClient.onMessage_1=globalThis.udpClient.onMessage_1 + globalThis.udpClient.onError_Callback(() => { + getUDP(context, true) + if (errorFlag && globalThis.udpClient && globalThis.udpClient.onMessage_1) { + globalThis.udpClient.onMessage_1 = globalThis.udpClient.onMessage_1 } }) getChuankouFn() @@ -82,11 +82,11 @@ export async function getUDP(context,errorFlag?) { globalThis.udpClient.rebindUdp(result[0].udplocalIp, result[0].udplocalIpPort, result[0].udpOppositeIp, result[0].udpOppositeIpPort) globalThis.udpClient.sendMsg('111', null) globalThis.host = `http://${result[0].centerIp}:${result[0].centerPort}` - globalThis.udpClient.onError_Callback(()=>{ + globalThis.udpClient.onError_Callback(() => { console.log('getUDPgetUDPgetUDP') - getUDP(true,context) - if(errorFlag&&globalThis.udpClient&&globalThis.udpClient.onMessage_1){ - globalThis.udpClient.onMessage_1=globalThis.udpClient.onMessage_1 + getUDP(true, context) + if (errorFlag && globalThis.udpClient && globalThis.udpClient.onMessage_1) { + globalThis.udpClient.onMessage_1 = globalThis.udpClient.onMessage_1 } }) reslove(`http://${result[0].centerIp}:${result[0].centerPort}`) @@ -105,14 +105,14 @@ export async function getUDP(context,errorFlag?) { globalThis.host = `http://${result[0].centerIp}:${result[0].centerPort}` globalThis.udpClient = udpClient - globalThis.udpClient.onMessage_1(()=>{ + globalThis.udpClient.onMessage_1(() => { console.log('getUDPonMessage_1msgmsgByGloalUdp') }) - globalThis.udpClient.onError_Callback(()=>{ - getUDP(true,context) - if(errorFlag&&globalThis.udpClient&&globalThis.udpClient.onMessage_1){ - globalThis.udpClient.onMessage_1=globalThis.udpClient.onMessage_1 + globalThis.udpClient.onError_Callback(() => { + getUDP(true, context) + if (errorFlag && globalThis.udpClient && globalThis.udpClient.onMessage_1) { + globalThis.udpClient.onMessage_1 = globalThis.udpClient.onMessage_1 } }) // udpClient.onError_resend(globalThis.udpClient.onMessage_1?globalThis.udpClient.onMessage_1:()=>{}) @@ -140,25 +140,25 @@ export async function getUDP(context,errorFlag?) { } -export async function getUDP2(context,errorFlag?) { +export async function getUDP2(context, errorFlag?) { const fileUtil = new FileUtil(context) const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); if (data === '' || data === undefined) { globalThis.udpClient2 = {} globalThis.udpClient2.setMsgCallBack = () => { } - }else{ - const result=JSON.parse(data) + } else { + const result = JSON.parse(data) console.log(` getUDP2 has IPConfigTable `); if (globalThis.udpClient2 && globalThis.udpClient2.closeUdp) { console.log(` getUDP2 has udclent ,close and rebind `); globalThis.udpClient2.closeUdp(async () => { setTimeout(() => { globalThis.udpClient2.rebindUdp(result.udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) - globalThis.udpClient2.onError_Callback(()=>{ - getUDP2(context,true); - if(errorFlag&&globalThis.udpClient2&&globalThis.udpClient2.onMessage_2){ - globalThis.udpClient2.onMessage_2=globalThis.udpClient2.onMessage_2 + globalThis.udpClient2.onError_Callback(() => { + getUDP2(context, true); + if (errorFlag && globalThis.udpClient2 && globalThis.udpClient2.onMessage_2) { + globalThis.udpClient2.onMessage_2 = globalThis.udpClient2.onMessage_2 } }) }, 1000) @@ -169,33 +169,37 @@ export async function getUDP2(context,errorFlag?) { console.log(` getUDP2 has no udclent and bind `); const udpClient2: UdpClientByCenter = new UdpClientByCenter(result.udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) console.info('surenjun udp2=> ', globalThis.carInfo?.messagePort) - await udpClient2.bindUdp() - await udpClient2.onError_Callback(()=>{ - getUDP2(context,true); - if(errorFlag&&globalThis.udpClient2&&globalThis.udpClient2.onMessage_2){ - globalThis.udpClient2.onMessage_2=globalThis.udpClient2.onMessage_2 + udpClient2.bindUdp() + udpClient2.onError_Callback(() => { + getUDP2(context, true); + if (errorFlag && globalThis.udpClient2 && globalThis.udpClient2.onMessage_2) { + globalThis.udpClient2.onMessage_2 = globalThis.udpClient2.onMessage_2 } }) - if(!errorFlag){ - await udpClient2.onMessage_2((val) => { + if (!errorFlag) { + udpClient2.onMessage_2((val) => { console.log('getUDPOnmessageByGlobalUDP2Message') + if (val.id == '18') { + uploadLogFile() + } if (val.id == '32') { globalThis.signNum = val.body[1] - if(val.body[0] == 5){ + if (val.body[0] == 5) { console.info('surenjun', `接收到平台扣分请求,请求指令为:${val.body[1]}`) globalThis.udpEvent.sendOnKf(val.body[1]) } - if(val.body[0] == 11){ - console.info('surenjun','GlobalUdp收到beginExam事件') + if (val.body[0] == 11) { + console.info('surenjun', 'GlobalUdp收到beginExam事件') globalThis.udpEvent.sendBeginExam(val.body[1]) } - if(val.body[0] == 12){ - console.info('surenjun','GlobalUdp收到endExam事件') + if (val.body[0] == 12) { + console.info('surenjun', 'GlobalUdp收到endExam事件') globalThis.udpEvent.sendEndExam(val.body[1]) } - }if (val.id == '36'){ + } + if (val.id == '36') { //获取远程扣分内容 - console.info('surenjun','考车收到远程扣分项目内容,扣分代码:' + val.body[0]) + console.info('surenjun', '考车收到远程扣分项目内容,扣分代码:' + val.body[0]) globalThis.udpEvent.sendKfContent(val.body[0]) } else if (val.id == '46') { let tmpList = [] @@ -227,10 +231,10 @@ export async function getUDP2(context,errorFlag?) { globalThis.udpClient2.closeUdp(async () => { setTimeout(() => { globalThis.udpClient2.rebindUdp(result[0].udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) - globalThis.udpClient2.onError_Callback(()=>{ + globalThis.udpClient2.onError_Callback(() => { getUDP2(true); - if(errorFlag&&globalThis.udpClient2&&globalThis.udpClient2.onMessage_2){ - globalThis.udpClient2.onMessage_2=globalThis.udpClient2.onMessage_2 + if (errorFlag && globalThis.udpClient2 && globalThis.udpClient2.onMessage_2) { + globalThis.udpClient2.onMessage_2 = globalThis.udpClient2.onMessage_2 } }) }, 1000) @@ -241,13 +245,13 @@ export async function getUDP2(context,errorFlag?) { console.log(` getUDP2 has no udclent and bind `); const udpClient2: UdpClientByCenter = new UdpClientByCenter(result[0].udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) await udpClient2.bindUdp() - await udpClient2.onError_Callback(()=>{ + await udpClient2.onError_Callback(() => { getUDP2(true); - if(errorFlag&&globalThis.udpClient2&&globalThis.udpClient2.onMessage_2){ - globalThis.udpClient2.onMessage_2=globalThis.udpClient2.onMessage_2 + if (errorFlag && globalThis.udpClient2 && globalThis.udpClient2.onMessage_2) { + globalThis.udpClient2.onMessage_2 = globalThis.udpClient2.onMessage_2 } }) - if(!errorFlag){ + if (!errorFlag) { await udpClient2.onMessage_2((val) => { if (val.id == '32') { globalThis.signNum = val.body[1] @@ -321,11 +325,13 @@ export async function setJudgeUdp() { globalThis.carInfo?.udpAddress, globalThis.carInfo?.hintPort ) - console.info('surenjun hintPort=> ',globalThis.carInfo?.hintPort) + console.info('surenjun hintPort=> ', globalThis.carInfo?.hintPort) - await udpClientbyCenter.onError_Callback(()=>{}) + await udpClientbyCenter.onError_Callback(() => { + }) await udpClientbyCenter.bindUdp() - await udpClientbyCenter.onMessage_2((val) => {}) + await udpClientbyCenter.onMessage_2((val) => { + }) //远程监听开始考试、结束考试、扣分指令 @@ -344,7 +350,7 @@ export async function setJudgeUdp() { }, //申请远程扣分查询 - askKf(directives){ + askKf(directives) { globalThis.udpClient2.sendMsgExt({ id: 35, list: [directives], @@ -355,10 +361,10 @@ export async function setJudgeUdp() { }, //确定远程扣分 - confirmKf(directives,code){ + confirmKf(directives, code) { globalThis.udpClient2.sendMsgExt({ id: 37, - list: Array2Byte([string2Bytes(directives,8),string2Bytes(code,8)]), + list: Array2Byte([string2Bytes(directives, 8), string2Bytes(code, 8)]), carNo: globalThis.carInfo.carNo, placeId: globalThis.carInfo.examinationRoomId }) @@ -368,4 +374,5 @@ export async function setJudgeUdp() { } } + // globalThis.udpClient.bindUdp() diff --git a/entry/src/main/ets/common/utils/request.ts b/entry/src/main/ets/common/utils/request.ts index 479c9b9a..93900c5c 100644 --- a/entry/src/main/ets/common/utils/request.ts +++ b/entry/src/main/ets/common/utils/request.ts @@ -2,12 +2,12 @@ import http from '@ohos.net.http'; import convertxml from '@ohos.convertxml'; import prompt from '@ohos.prompt' import { sendGreen } from '../../pages/judgeSDK/utils/judgeCommon'; -import {GlobalConfig} from '../../config/index' +import { GlobalConfig } from '../../config/index' import FileUtil from '../../common/utils/File'; import { dateFormat } from '../utils/tools' const config = { - host:GlobalConfig.host, + host: GlobalConfig.host, } let httpRequest = http.createHttp(); @@ -24,219 +24,225 @@ let httpRequest = http.createHttp(); */ export default async function request(req: any) { - const {url,params = {},data = {},xml,method = 'get',host,isNewCenter = false} = req; - const options = { - method: http.RequestMethod[method.toUpperCase()], - header: { - 'Content-Type': xml ? 'text/xml' : 'application/json' - }, - extraData: xml ? data : JSON.stringify(data) + const {url,params = {},data = {},xml,method = 'get',host,isNewCenter = false} = req; + const options = { + method: http.RequestMethod[method.toUpperCase()], + header: { + 'Content-Type': xml ? 'text/xml' : 'application/json' + }, + extraData: xml ? data : JSON.stringify(data) + } + //params转url拼接参数 + let paramsStr = Reflect.ownKeys(params).reduce((p: string, n: string) => (`${p}${n}=${params[n]}&`), '?') || ''; + paramsStr = paramsStr.toString(); + paramsStr = paramsStr.substring(0, paramsStr.length - 1) + try { + let baseUrl = host ? host : globalThis.host + + console.log('request 请求地址' + baseUrl, url) + + const {result} = await httpRequest.request(`${baseUrl}${url}${paramsStr}`, options); + + console.log('request 响应结果' + JSON.stringify(result)) + let res: any = xml ? xmlToJson(result, url) : result; + console.log('request 响应JSON串' + JSON.stringify(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); + return dd } - //params转url拼接参数 - let paramsStr = Reflect.ownKeys(params).reduce((p: string, n: string) => (`${p}${n}=${params[n]}&`), '?') || ''; - paramsStr = paramsStr.toString(); - paramsStr = paramsStr.substring(0, paramsStr.length-1) - try { - let baseUrl=host?host:globalThis.host - // let baseUrl=host?config.csptHost:config.host' - console.log('响应头地址' + baseUrl,url) - - const {result,responseCode} = await httpRequest.request(`${baseUrl}${url}${paramsStr}`, options); - // fileUtil.editFile(`${folderPath}/request.txt`, JSON.stringify(arrList)) - // writeLog({ - // time:dateFormat(new Date()), - // url, - // result:JSON.stringify(result), - // extraData: JSON.stringify(data), - // state:'end' - // }) - console.log('响应头地址' + JSON.stringify(result)) - let res:any = xml ? xmlToJson(result,url) : result; - console.log('响应头地址' + JSON.stringify(res)) - - let resObj = null; - if(typeof res === "string"){ - res=JSON.parse(res) - } - //处理中心服务code - if(res.Envelope){ - const msgXml = res.Envelope.Body.writeObjectOutResponse.return; - //Envelope.Body.writeObjectOutResponse.return - const dd = handleCenterCode(msgXml,isNewCenter); - return dd - } - - if(!xml){ - if(res.head.resultCode === '0'){ - return res - }else{ - const resultMessage = res?.body?.resultMessage || res?.head?.resultMessage - prompt.showToast({ - message: decodeURIComponent(resultMessage), - duration: 3000 - }); - return false - } - } - for( let i in res ) { - resObj = res[i].head - } - console.info('jiangsong:res in request' + url + JSON.stringify(resObj)) - if(resObj.resultCode === '0') { - return res - }else { - prompt.showToast({ - message: decodeURIComponent(resObj.resultMessage), - duration: 3000 - }); - return res - } - } catch (e) { - console.info('surenjunerror',JSON.stringify(e)) - if(!e||!(e?.message)){ - return false - } - const code = e?.code; + if (!xml) { + if (res.head.resultCode === '0') { + return res + } else { + const resultMessage = res?.body?.resultMessage || res?.head?.resultMessage prompt.showToast({ - message: e?.message, - duration: 5000 + message: decodeURIComponent(resultMessage), + duration: 3000 }); - switch (code){ - //断网 - case 2300007: return 2300007 - default: - } return false - console.info('test-error' + url + ' error:resp: '+ JSON.stringify(e)) - httpRequest.destroy(); + } } + for (let i in res) { + resObj = res[i].head + } + console.info('jiangsong:res in request' + url + JSON.stringify(resObj)) + if (resObj.resultCode === '0') { + return res + } else { + prompt.showToast({ + message: decodeURIComponent(resObj.resultMessage), + duration: 3000 + }); + return res + } + } catch (e) { + console.info('surenjunerror', JSON.stringify(e)) + if (!e || !(e?.message)) { + return false + } + const code = e?.code; + prompt.showToast({ + message: e?.message, + duration: 5000 + }); + switch (code) { + //断网 + case 2300007: + return 2300007 + default: + } + return false + console.info('test-error' + url + ' error:resp: ' + JSON.stringify(e)) + httpRequest.destroy(); + } } -async function writeLog(param){ - const fileUtil = new FileUtil(globalThis.context) - const folderPath = await fileUtil.initFolder(`/errorMsg/`); - fileUtil.editFile(`${folderPath}/request.txt`, JSON.stringify(param)+`\n`) + +async function writeLog(param) { + const fileUtil = new FileUtil(globalThis.context) + const folderPath = await fileUtil.initFolder(`/errorMsg/`); + fileUtil.editFile(`${folderPath}/request.txt`, JSON.stringify(param) + `\n`) } + //xml格式转JSON -function xmlToJson(result,url) { - console.log("xmlToJson begin",url); - let xmlOptions = {trim : false, declarationKey:"_declaration", - instructionKey : "_instruction", attributesKey : "_attributes", - textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", - commentKey : "_comment", parentKey : "_parent", typeKey : "_type", - nameKey : "_name", elementsKey : "_elements", "skipPreprocess" : true} +function xmlToJson(result, url) { + console.log("xmlToJson begin", url); + let xmlOptions = { + trim: false, + declarationKey: "_declaration", + instructionKey: "_instruction", + attributesKey: "_attributes", + textKey: "_text", + cdataKey: "_cdata", + doctypeKey: "_doctype", + commentKey: "_comment", + parentKey: "_parent", + typeKey: "_type", + nameKey: "_name", + elementsKey: "_elements", + "skipPreprocess": true + } - let strXml = result.toString(); - let conv = new convertxml.ConvertXML(); + let strXml = result.toString(); + let conv = new convertxml.ConvertXML(); - console.log("xmlToJson result.length = " + result.length); - console.log("xmlToJson result content = " + result); - // @ts-ignore - let {_elements:xmlArr} = conv.convertToJSObject(strXml, xmlOptions); - console.log("xmlToJson deeml begin"); - let res = deeml(xmlArr); - console.log("xmlToJson end",url); - return res + console.log("xmlToJson result.length = " + result.length); + console.log("xmlToJson result content = " + result); + // @ts-ignore + let {_elements:xmlArr} = conv.convertToJSObject(strXml, xmlOptions); + console.log("xmlToJson deeml begin"); + let res = deeml(xmlArr); + console.log("xmlToJson end", url); + return res } //处理中心服务code -function handleCenterCode(msgXml,isNewCenter){ - //新监管 - if(isNewCenter){ - const msg = JSON.parse(msgXml); - const result = msg?.data[0]?.result; - if(result){ - const {code,message,retval} = result - if(code != '1'){ - const rMessage = decodeURIComponent(message as string) - // globalThis.title=rMessage - // globalThis.type='1' - // globalThis.errorDialog.open() - prompt.showToast({ - message:rMessage, - duration: 3000 - }); - return {code,message} - }else{ - return { code ,keystr:retval} - } - } - } - - //正则匹配code message字段 - const [code,message,keystr] = [/(.*)<\/code>/i,/(.*)<\/message>/i,/(.*)<\/keystr>/i].map(pattern=>{ - const patternArr = pattern.exec(msgXml); - return patternArr && patternArr[1] - }); - - if(code != '1'){ - prompt.showToast({ - message: decodeURIComponent(message as string), - duration: 3000 - }); +function handleCenterCode(msgXml, isNewCenter) { + //新监管 + if (isNewCenter) { + const msg = JSON.parse(msgXml); + const result = msg?.data[0]?.result; + if (result) { + const {code,message,retval} = result + if (code != '1') { + const rMessage = decodeURIComponent(message as string) + // globalThis.title=rMessage // globalThis.type='1' - // globalThis.title=decodeURIComponent(message as string) // globalThis.errorDialog.open() - return {code,message:decodeURIComponent(message)} - }else{ - return { code ,keystr, message } + prompt.showToast({ + message: rMessage, + duration: 3000 + }); + return { code, message } + } else { + return { code, keystr: retval } + } } + } + + //正则匹配code message字段 + const [code, message, keystr] = [/(.*)<\/code>/i, /(.*)<\/message>/i, /(.*)<\/keystr>/i].map(pattern => { + const patternArr = pattern.exec(msgXml); + return patternArr && patternArr[1] + }); + + if (code != '1') { + prompt.showToast({ + message: decodeURIComponent(message as string), + duration: 3000 + }); + // globalThis.type='1' + // globalThis.title=decodeURIComponent(message as string) + // globalThis.errorDialog.open() + return { code, message: decodeURIComponent(message) } + } else { + return { code, keystr, message } + } } //JSON转xml格式 -const deeml = (elements,_name?)=>{ - const json = {} +const deeml = (elements, _name?) => { + const json = {} - elements.map(ele =>{ - const _elements = ele._elements - if(ele._type === 'element'){ - if(_elements==undefined){ - return - } - const thisJson = json[ele._name] - if(_elements && _elements.length === 1 && _elements[0]._type === 'text'){ - // 如果值存在了 - if(thisJson){ - handleCommonArr(_elements[0]._text) - }else{ - json[ele._name] = _elements[0]._text - } - }else{ - if(thisJson){ - handleCommonArr( deeml(ele._elements,ele._name) ) - }else{ - json[ele._name] = deeml(ele._elements,ele._name) - } - } - - //通用处理重复标签 - function handleCommonArr(obj){ - if(thisJson){ - if(Array.isArray(thisJson)){ - json[ele._name].push(obj) - }else{ - json[ele._name] = [json[ele._name],obj] - } - }else{ - json[ele._name] = obj - } - }0 - }else{ - //标签上有属性 - if(ele._attributes){ - json[_name] = { - value: ele._text, - attributes:ele.__attributes - } - } + elements.map(ele => { + const _elements = ele._elements + if (ele._type === 'element') { + if (_elements == undefined) { + return + } + const thisJson = json[ele._name] + if (_elements && _elements.length === 1 && _elements[0]._type === 'text') { + // 如果值存在了 + if (thisJson) { + handleCommonArr(_elements[0]._text) + } else { + json[ele._name] = _elements[0]._text } + } else { + if (thisJson) { + handleCommonArr(deeml(ele._elements, ele._name)) + } else { + json[ele._name] = deeml(ele._elements, ele._name) + } + } - }); - return json + //通用处理重复标签 + function handleCommonArr(obj) { + if (thisJson) { + if (Array.isArray(thisJson)) { + json[ele._name].push(obj) + } else { + json[ele._name] = [json[ele._name], obj] + } + } else { + json[ele._name] = obj + } + } + + 0 + } else { + //标签上有属性 + if (ele._attributes) { + json[_name] = { + value: ele._text, + attributes: ele.__attributes + } + } + } + + }); + return json }; function isEmpty(param) { - return!Object.keys(param).length; + return !Object.keys(param).length; } diff --git a/entry/src/main/ets/pages/Index.ets b/entry/src/main/ets/pages/Index.ets index c981d70f..6506d416 100644 --- a/entry/src/main/ets/pages/Index.ets +++ b/entry/src/main/ets/pages/Index.ets @@ -3,7 +3,6 @@ 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'; @@ -11,7 +10,12 @@ 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, uploadLogFile,compressFile } from '../common/service/indexService'; +import { + getliushuiNum, + setliushuiNum, + takePhotoFn, + uploadLogFile, +} from '../common/service/indexService'; import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import worker, { MessageEvents } from '@ohos.worker'; import promptAction from '@ohos.promptAction' @@ -20,8 +24,6 @@ import errorMsgDialog from './compontents/errorMsgDialog' import { getSyncData } from '../common/service/initable'; import GetDistance from '../common/utils/GetDistance' 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 @@ -29,15 +31,7 @@ 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 @Component @@ -82,7 +76,6 @@ struct Index { .height(69 * this.ratio * this.dialogRatio) .backgroundImage($r('app.media.button_nor')) .backgroundImageSize({ width: '100%', height: '100%' }) - // .margin({ bottom: 12 * this.ratio }) } build() { @@ -93,8 +86,7 @@ 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') + await uploadLogFile() if (this.loading) { return } @@ -335,8 +327,9 @@ struct Index { globalThis.udpEvent = new UdpEvent(); } + // 解压 unzip(inFile: string, outFile: string) { - return new Promise((reslove, reject) => { + return new Promise((resolve, reject) => { let options: zlib.Options = { level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, @@ -349,24 +342,21 @@ struct Index { if (errData !== null) { console.log('解压失败') reject(false) - // Prompt.showToast({ message: '题库解压失败errCode:' + errData.code, duration: 2000 }) } - // 解压完成删除压缩包 - // if (fs.accessSync(inFile)) { - // fs.unlinkSync(inFile); - // } - reslove(true) + if (fs.accessSync(inFile)) { + fs.unlinkSync(inFile); + } + resolve(true) }) - } catch (errData) { - console.log('解压成功error', errData) + } catch (err) { + console.error('解压失败error', err) reject(false) - } }) - } - async installBoundle() { + // 安装 + async installBundle() { let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/entry-default-signed.hap']; let installParam: installer.InstallParam = { userId: 100, @@ -397,10 +387,6 @@ struct Index { return } - // let mode=globalThis.timeInfo?.mode?globalThis.timeInfo?.mode:1 - - // console.log('mode',mode) - let workerInstance = new worker.ThreadWorker('entry/ets/workers/worker.ts'); const param = { carId: globalThis.carInfo?.carId, @@ -523,7 +509,6 @@ struct Index { this.fileHelper = new FileHelper(); this.fileHelper.createAlbum('jt') this.fileHelper.createAlbum('pz'); - } userAuth() { @@ -550,19 +535,19 @@ struct Index { }) } - requestDownload(httpPath, path, outFile,flag?) { + 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.loading = false this.unzip(path, outFile) }) - if(!flag){ - this.mxwjDownloadFlag=false + if (!flag) { + this.mxwjDownloadFlag = false } }).catch(error => { @@ -571,8 +556,9 @@ struct Index { } - //flage true hap包 false 模型文件 + //flag true hap包 false 模型文件 async getModalValueCdAndCar(flag) { + this.loading = true const data = await getModalValueCdAndCar({ carid: globalThis.carInfo.carId, kdid: globalThis.timeInfo?.paraKdid || globalThis.timeInfo?.kdid @@ -582,11 +568,13 @@ struct Index { 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 + if (data.version !== globalThis.version) { + path = '/data/storage/el2/base/haps/entry/files/' + arr[arr.length-1] + this.requestDownload(httpPath, path, outFile, flag) + return + } } else { - this.mxwjDownloadFlag=true + 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/`); @@ -594,16 +582,13 @@ struct Index { const fileUtil = new FileUtil(this.context) const folderPath = await fileUtil.initFolder(`/models/`); path = folderPath + '/' + arr[arr.length-1] - this.requestDownload(httpPath, path, outFile,flag) + 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) @@ -633,6 +618,8 @@ struct Index { this.heartMsg() } }, 1000) + this.getModalValueCdAndCar(true) + //下载模型 // await this.getModel() // const arr = [0x55, 0xaa, 0x01, 0x00, 0x02, 0x01, 0x03, 0x00]