日志打包上传

This commit is contained in:
lixiao 2024-12-18 09:14:10 +08:00
parent 4b2094a97a
commit 092cab3032
4 changed files with 377 additions and 368 deletions

View File

@ -3,14 +3,11 @@ import promptAction from '@ohos.promptAction'
import router from '@ohos.router'
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,
@ -26,56 +23,95 @@ import fs from '@ohos.file.fs';
let num = 0
async function copyFileSync(fileUrl) {
return new Promise(async(reslove,reject)=>{
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);
console.log('realUrirealUri',realUri)
fs.copyFileSync(file.fd, realUri)
reslove()
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])
fs.copyFileSync('/data/log/hilog/' + filenames[i], globalThis.context.cacheDir + '/temp/' + filenames[i])
}
}
}
//轨迹压缩拷贝到cache地址
// const date=time.split(' ')[0].split('-').join('_')
}
// 将要上传的文件拷贝到缓存目录并压缩
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 = `/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);
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(fileUrl) {
getCopyFiles()
return
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()
return zlib.compressFile(inFile, outFile, options)
}
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) {
@ -347,7 +357,6 @@ export async function getSingleCenterTable(param) {
}
let interval
export async function takePhotoFn(context) {

View File

@ -1,7 +1,7 @@
//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'
@ -169,16 +169,19 @@ 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(()=>{
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) => {
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) {
@ -193,7 +196,8 @@ export async function getUDP2(context,errorFlag?) {
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])
globalThis.udpEvent.sendKfContent(val.body[0])
@ -323,9 +327,11 @@ export async function setJudgeUdp() {
)
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) => {
})
//远程监听开始考试、结束考试、扣分指令
@ -368,4 +374,5 @@ export async function setJudgeUdp() {
}
}
// globalThis.udpClient.bindUdp()

View File

@ -38,22 +38,14 @@ export default async function request(req: any) {
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)
console.log('request 请求地址' + 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))
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('响应头地址' + JSON.stringify(res))
console.log('request 响应JSON串' + JSON.stringify(res))
let resObj = null;
if (typeof res === "string") {
@ -62,7 +54,6 @@ export default async function request(req: any) {
//处理中心服务code
if (res.Envelope) {
const msgXml = res.Envelope.Body.writeObjectOutResponse.return;
//Envelope.Body.writeObjectOutResponse.return
const dd = handleCenterCode(msgXml, isNewCenter);
return dd
}
@ -104,7 +95,8 @@ export default async function request(req: any) {
});
switch (code) {
//断网
case 2300007: return 2300007
case 2300007:
return 2300007
default:
}
return false
@ -113,20 +105,32 @@ export default async function request(req: any) {
}
}
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}
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();
@ -222,7 +226,9 @@ const deeml = (elements,_name?)=>{
} else {
json[ele._name] = obj
}
}0
}
0
} else {
//标签上有属性
if (ele._attributes) {

View File

@ -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() {
@ -556,9 +541,9 @@ struct Index {
filePath: path
})
.then((downloadTask) => {
console.log('响应头地址downloadsucces')
downloadTask.on('complete', async () => {
console.info('download complete');
this.loading = false
this.unzip(path, outFile)
})
if (!flag) {
@ -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,9 +568,11 @@ struct Index {
const arr = httpPath.split('/')
let path
if (flag) {
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
const res = fs.accessSync('/mnt/hmdfs/100/account/device_view/local/files/models/')
@ -601,9 +589,6 @@ struct Index {
}
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]