diff --git a/.gitignore b/.gitignore index a6da3e53..61221726 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,6 @@ /.clang-tidy /entry/src/main/cpp /entry/src/main/ets/pages/judgeSDK/utils/judgeConfig.ts -/build-profile.json5 \ No newline at end of file +build-profile.json5 +/entry/oh-package-lock.json5 +oh-package-lock.json5 \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..10174537 --- /dev/null +++ b/Makefile @@ -0,0 +1,23 @@ +TOOLCHAIN_PATH := /Users/wangzhongjie/Library/OpenHarmony/Sdk/9/toolchains + +logs: + cd $(TOOLCHAIN_PATH) && \ + ./hdc file recv /mnt/hmdfs/100/account/device_view/local/files/duolun/logs /Users/wangzhongjie/Desktop/log + +hilog: + cd $(TOOLCHAIN_PATH) && \ + ./hdc kill && \ + ./hdc shell "tar -czvf /data/log.tar.gz /data/log/" && \ + ./hdc file recv /data/log.tar.gz /Users/wangzhongjie/Desktop/log && \ + ./hdc shell "rm -rf /data/log.tar.gz" + +open: + cd $(TOOLCHAIN_PATH) && \ + ./hdc kill && \ + ./hdc shell hilog -w stop && \ + ./hdc shell hilog -r && \ + ./hdc shell hilog -w start -l 100M -m none && \ + ./hdc shell hilog -Q pidoff && \ + ./hdc shell hilog -p off && \ + ./hdc shell hilog -b D && \ + ./hdc shell hilog -w start -t kmsg -m none \ No newline at end of file diff --git a/build-profile.json5 b/build-profile.json5 index 5d0750fa..c1c4a9d5 100644 --- a/build-profile.json5 +++ b/build-profile.json5 @@ -4,13 +4,13 @@ { "name": "default", "material": { - "certpath": "/Users/surenjun/.ohos/config/openharmony/auto_ohos_default_subject-two_com.oh.dts.cer", - "storePassword": "0000001BE4BBADDF656A884E7A7BB5FD51F64FBB61DD24A944FEA969482DD693210ED5FF3D29F13642E3A3", + "certpath": "/Users/wangzhongjie/.ohos/config/openharmony/default_subject-two_Kl4t-ZSvZeuUm9s8O-e6FIH2VFR_OaNyhDP8kPjIWgU=.cer", + "storePassword": "0000001B0A8E97F78561FFE1B2E5B57C296BFC3D297047253237158BC25CD7077892C41C1C83FAFFDE4A0A", "keyAlias": "debugKey", - "keyPassword": "0000001BDEFFDC280B45617E7FC447CB21F2D133540301F543454643D3F5E9F6E5ED2A583A7FA92B260433", - "profile": "/Users/surenjun/.ohos/config/openharmony/auto_ohos_default_subject-two_com.oh.dts.p7b", + "keyPassword": "0000001B654E765B79C902CB9E3A6D97A40F5852412CEE5AC37E949F430C754DB02327838E925EDF861314", + "profile": "/Users/wangzhongjie/.ohos/config/openharmony/default_subject-two_Kl4t-ZSvZeuUm9s8O-e6FIH2VFR_OaNyhDP8kPjIWgU=.p7b", "signAlg": "SHA256withECDSA", - "storeFile": "/Users/surenjun/.ohos/config/openharmony/auto_ohos_default_subject-two_com.oh.dts.p12" + "storeFile": "/Users/wangzhongjie/.ohos/config/openharmony/default_subject-two_Kl4t-ZSvZeuUm9s8O-e6FIH2VFR_OaNyhDP8kPjIWgU=.p12" } } ], diff --git a/entry/build-profile.json5 b/entry/build-profile.json5 index 2160ea13..6cfa095d 100644 --- a/entry/build-profile.json5 +++ b/entry/build-profile.json5 @@ -2,6 +2,11 @@ "apiType": 'stageMode', "buildOption": { "externalNativeOptions": { + "abiFilters": [ + "arm64-v8a", + "armeabi-v7a", + "x86_64" + ], "path": "./src/main/cpp/CMakeLists.txt", "arguments": "", "cppFlags": "", diff --git a/entry/oh-package-lock.json5 b/entry/oh-package-lock.json5 index bc40219d..1f023b33 100644 --- a/entry/oh-package-lock.json5 +++ b/entry/oh-package-lock.json5 @@ -1,13 +1,15 @@ { - "lockfileVersion": 1, + "lockfileVersion": 2, "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", "specifiers": { "@ohos/hypium@1.0.6": "@ohos/hypium@1.0.6" }, "packages": { "@ohos/hypium@1.0.6": { - "resolved": "https://repo.harmonyos.com/ohpm/@ohos/hypium/-/hypium-1.0.6.tgz", - "integrity": "sha512-bb3DWeWhYrFqj9mPFV3yZQpkm36kbcK+YYaeY9g292QKSjOdmhEIQR2ULPvyMsgSR4usOBf5nnYrDmaCCXirgQ==" + "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.6.tgz", + "integrity": "sha512-bb3DWeWhYrFqj9mPFV3yZQpkm36kbcK+YYaeY9g292QKSjOdmhEIQR2ULPvyMsgSR4usOBf5nnYrDmaCCXirgQ==", + "registryType": "ohpm", + "shasum": "3f5fed65372633233264b3447705b0831dfe7ea1" } } } \ No newline at end of file diff --git a/entry/src/main/ets/api/index.ts b/entry/src/main/ets/api/index.ts index 1e114e86..591b61b8 100644 --- a/entry/src/main/ets/api/index.ts +++ b/entry/src/main/ets/api/index.ts @@ -110,4 +110,25 @@ export async function initCarParameter(params){ method:'post', xml:false, }) +} + +//模型&软件下载 +export async function getModalValueCdAndCar(params) { + return await request({ + url: '/der2/services/data/getModalValueCdAndCar.ws', + data: ` + + + + + + + ${params.carid} + 1 + 3 + +`, + method: 'post', + xml: true, + }) } \ No newline at end of file diff --git a/entry/src/main/ets/common/autoUpdate/index.ts b/entry/src/main/ets/common/autoUpdate/index.ts new file mode 100644 index 00000000..7280ec8a --- /dev/null +++ b/entry/src/main/ets/common/autoUpdate/index.ts @@ -0,0 +1,149 @@ +import request from '@ohos.request' +import fs from '@ohos.file.fs' +import zlib from '@ohos.zlib'; +import installer from '@ohos.bundle.installer'; +import { getModalValueCdAndCar } from '../../api'; +import FileUtil from '../../common/utils/File'; +// @ts-ignore +import { BusinessError } from '@ohos.base'; + +const TAG = '[updateModelAndCar]' +//flag true hap包 false 模型文件 +export async function updateModelAndCar(flag){ + const data:any = await getModalValueCdAndCar({ carid: globalThis.carInfo.carId }) + + const outFile = flag ? '/data/storage/el2/base/haps/entry/files/' : '/mnt/hmdfs/100/account/device_view/local/files/duolun/models' + const httpPath = flag ? data.getModalValueCdAndCarRsp.body.appPath : data.getModalValueCdAndCarRsp.body.filePath + const arr = httpPath.split('/') + let path + if (flag) { + console.info('outFile=>',outFile) + console.info('httpPath=>',httpPath) + path = '/data/storage/el2/base/haps/entry/files/' + arr[arr.length-1] + const isHapExit = fs.accessSync('/data/storage/el2/base/haps/entry/files/entry-default-signed.hap'); + const isZipExit = fs.accessSync(path); + console.info(TAG,'entry-default-signed.hap文件是否存在'+isHapExit) + console.info( TAG,`${arr[arr.length-1]}文件是否存在`+isZipExit,) + if(isHapExit){ + fs.unlinkSync('/data/storage/el2/base/haps/entry/files/entry-default-signed.hap') + } + return requestDownload(httpPath, path, outFile, flag) + } else { + const fileUtil = new FileUtil(globalThis.context) + await fileUtil.initFolder(`/models`); + await fileUtil.deleteF('models',1) + const folderPath = await fileUtil.initFolder(`/models`); + path = folderPath + '/' + arr[arr.length-1] + return requestDownload(httpPath, path, outFile, flag) + } + +} + +// 安装 +export async function installBundle() { + // let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/entry-default-signed.hap']; + 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) => { + console.info(TAG,'开始安装') + data.install(hapFilePaths, installParam, (err: BusinessError) => { + if (err) { + console.error(TAG,'install failed:' + err.message); + } else { + console.info(TAG,'install successfully.'); + } + }); + }).catch((error: BusinessError) => { + console.error(TAG,'getBundleInstaller failed. Cause: ' + error.message); + }); + } catch (error) { + let message = (error as BusinessError).message; + console.error(TAG,'getBundleInstaller failed. Cause: ' + message); + } +} + +// 解压 +export function unzip(inFile: string, outFile: string) { + return new Promise((resolve, 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(TAG,'开始解压文件'); + zlib.decompressFile(inFile, outFile, options, (errData) => { + if (errData !== null) { + console.log(TAG,'解压失败') + reject(false) + } + console.log(TAG,'解压成功',) + if (fs.accessSync(inFile)) { + fs.unlinkSync(inFile); + } + resolve(true) + }) + } catch (err) { + console.error(TAG,'解压失败error' + JSON.stringify(err), ) + reject(false) + } + }) +} + +export async function requestDownload(httpPath, path, outFile, flag?) { + const url = 'http://' + (globalThis.host).match(/^(?:https?:\/\/)?(?:\[([0-9a-fA-F:]+)\]|([0-9.]+))(?::\d+)?/)[2] +':8080'+ httpPath.match(/^https?:\/\/[^\/]+(\/[^?#]*)/)[1] + console.info(TAG,'httpPath=>' + url) + console.info(TAG,'filePath=>' + path) + + return new Promise(async (resolve, reject) => { + + try { + // 需要手动将url替换为真实服务器的HTTP协议地址 + request.downloadFile(globalThis.context, { url, filePath: path }).then((data: request.DownloadTask) => { + let downloadTask: request.DownloadTask = data; + let timer = setInterval(async () => { + const info = await downloadTask.getTaskInfo(); + console.info(TAG,'app file download status: =>',info.status) + console.info(TAG,'app file download downloadedBytes: =>',info.downloadedBytes) + console.info(TAG,'app file download downloadTotalBytes: =>',info.downloadTotalBytes) + if(info.status === 0){ + await unzip(path, outFile) + if(flag){ + resolve(true) + installBundle() + } + resolve(true) + clearInterval(timer) + } + }, 1000); + // downloadTask.on('progress',async (receivedSize, totalSize: number)=>{ + // console.info(TAG,'receivedSize =>' + receivedSize) + // console.info(TAG,'totalSize =>' + totalSize) + // }) + // downloadTask.on('complete', async () => { + // console.info(TAG,'app file download complete') + // await unzip(path, outFile) + // if(flag){ + // installBundle() + // } + // resolve(true) + // }) + // downloadTask.on('fail', async () => { + // console.info(TAG,'app file download fail') + // return requestDownload(httpPath,path,outFile,flag) + // }) + }).catch((err: BusinessError) => { + console.error(TAG,`Failed to request the download. Code: ${err.code}` + `message: ${err.message}`); + }) + } catch (err) { + console.error(TAG,`Failed to request the download. err: ${JSON.stringify(err)}`); + } + + }) + +} \ No newline at end of file diff --git a/entry/src/main/ets/common/rearEndUnitsTool/aio/aioClass.ts b/entry/src/main/ets/common/rearEndUnitsTool/aio/aioClass.ts new file mode 100644 index 00000000..cbfe8b16 --- /dev/null +++ b/entry/src/main/ets/common/rearEndUnitsTool/aio/aioClass.ts @@ -0,0 +1,200 @@ +import systemTime from '@ohos.systemDateTime'; +import { PLCGPSData } from '../../../mock/PLCGPSData'; +import { + OpenSerialPort, + ReceiveSerialPortDataBySelf, + InitSerialPortData, + CancelReceiveSerialPortData, + SendSerialPortData, + CloseSerialPort, +} from '../../utils/aioTool' + +import { GlobalConfig } from '../../../config' + +export default class AIO { + obdFd: number + gpsFd: number + sensor: Object = {} + gps: Object = {} + obdStr: string = '' + gpsStr: string ='' + // 定位状态异常次数 + dwztErrorNumber:number = 0 + + constructor() { + this.init() + } + + async init() { + await this.getObd() + await this.getGps() + } + + public async getObd() { + //打开obd串口 + this.obdFd = await OpenSerialPort(GlobalConfig.serialPortConfig.obd.path); + //初始化串口 + await InitSerialPortData(this.obdFd, 115200); + + //发送一段数据 + const data = this.convertToASCII('LOG VERSION') + const res = await SendSerialPortData(this.obdFd, data) + + ReceiveSerialPortDataBySelf(this.obdFd, async (res1, res2, res3, res4) => { + // console.log(res1.toString(), res2.toString(), res3.toString(), "接受数据"); + let buffer = this.arrayToBuffer(res3) + let dataView = new DataView(buffer) + let str = "" + for (let i = 0; i < dataView?.byteLength; ++i) { + let c = String.fromCharCode(dataView?.getUint8(i)) + if (c !== "\n") { + str += c + } + } + // + // //获取档位信号 + // const {sensor} = plcStrToJson(str) + // this.sensor = sensor; + this.obdStr = str + }) + + } + + public async getGps() { + //打开gps串口 + this.gpsFd = await OpenSerialPort(GlobalConfig.serialPortConfig.gps.path); + //初始化串口 + await InitSerialPortData(this.gpsFd, 115200); + console.log('surenjun gpsFd=>',this.gpsFd) + ReceiveSerialPortDataBySelf(this.gpsFd, async (res1, res2, res3, res4) => { + // console.log(res1.toString(), res2.toString(), res3.toString(), "接受数据"); + let buffer = this.arrayToBuffer(res3) + let dataView = new DataView(buffer) + let str = "" + for (let i = 0; i < dataView?.byteLength; ++i) { + let c = String.fromCharCode(dataView?.getUint8(i)) + if (c !== "\n") { + str += c + } + } + this.gpsStr = str; + }) + } + + //副板gps端口重连 + public reConnect = async () => { + const {dwztErrorNumber,gpsFd,getGps} = this; + if(dwztErrorNumber >= 25){ + this.dwztErrorNumber = 0; + await CancelReceiveSerialPortData(gpsFd) + CloseSerialPort(gpsFd) + await getGps() + } + } + + //组装obd&gps数据 + public handleMsg() { + let newMessage = PLCGPSData; + + if (this.obdStr) { + const PLCByteArr = this.obdStr.split(',') + PLCByteArr.forEach((item, index) => { + newMessage[index] = item; + //档位 + if(index === 28){ + newMessage[28] = (globalThis.chuankoMsg == '0' || globalThis.chuankoMsg == '' ||globalThis.chuankoMsg == undefined)? item: globalThis.chuankoMsg + } + }) + } + if (this.gpsStr) { + + let GPGGAMatch = this.gpsStr.match(/\$GPGGA[^$]*/); + let GPGGAMsgArr = GPGGAMatch ? GPGGAMatch[0]?.split(",").slice(0, 15) : []; + // 使用正则提取$GPRMC消息 + let GPRMCMatch = this.gpsStr.match(/\$GPRMC[^$]*/); + let GPRMCMsgArr = GPRMCMatch ? GPRMCMatch[0]?.split(",").slice(0, 14) : []; + // 使用正则表达式提取$GPGST消息 + let GPGSTMatch = this.gpsStr.match(/\$GPGST[^$]*/); + let GPGSTMsgArr = GPGSTMatch ? GPGSTMatch[0]?.split(",").slice(0, 9) : []; + // 使用正则提取$PTNL消息 + let PTNLMatch = this.gpsStr.match(/\$PTNL[^$]*/); + let PTNLMsgArr = PTNLMatch ? PTNLMatch[0].split(",")?.slice(0, 14) : []; + + //@ts-ignore 板卡类型 + newMessage[56] = '1' + // 组合GPS数据 + // 状态83 + newMessage[83] = GPGGAMsgArr[6]; + // 收星数84 + newMessage[84] = GPGGAMsgArr[7]; + // 海拔高85 + newMessage[85] = GPGGAMsgArr[9]; + // 高度差86 + newMessage[86] = GPGGAMsgArr[11]; + // 龄期87 + newMessage[87] = GPGGAMsgArr[13]; + // 维度因子88 + newMessage[88] = GPGSTMsgArr[6]; + // 经度因子89 + newMessage[89] = GPGSTMsgArr[7] + // 航向角90 + newMessage[90] = PTNLMsgArr[3]; + // 俯仰角91 + newMessage[91] = PTNLMsgArr[5]; + // 航向角状态-收星数92 + newMessage[92] = PTNLMsgArr[10] + '-' + (PTNLMsgArr[12] && PTNLMsgArr[12].split('*')[0]); + // 年月日93 RMCMsgArr[9]为ddmmyy 日月年 转换为年月日 + newMessage[93] = + GPRMCMsgArr[9] && (GPRMCMsgArr[9].slice(0, 2) + GPRMCMsgArr[9].slice(2, 4) + GPRMCMsgArr[9].slice(4, 6)); + // 时分秒94 GPGGAMsgArr[1]为021126.00去掉小数点后的时间 + newMessage[94] = GPGGAMsgArr[1] && GPGGAMsgArr[1].replace(".", ""); + // 经度95 + newMessage[95] = GPGGAMsgArr[4]; + // 纬度96 + newMessage[96] = GPGGAMsgArr[2]; + // 速度97 + newMessage[97] = GPRMCMsgArr[7]; + } + + + return newMessage.map(item => { + return item === undefined?'':item + }).join(",") + } + // 关闭串口和监听 + public closeMessage = () => { + const {obdFd,gpsFd} = this; + CancelReceiveSerialPortData(obdFd) + CancelReceiveSerialPortData(gpsFd) + // CloseSerialPort(obdFd) + // CloseSerialPort(gpsFd) + } + + //发送差分改正数字 + public sendDiffCorrections = (data) => { + const {gpsFd} = this; + let arr = [] + if(data?.byteLength){ + // console.info('surenjun 一体机发送差分数据',data?.byteLength) + let dataView = new DataView(data) + let str = "" + for (let i = 0; i < dataView?.byteLength; ++i) { + arr.push(dataView?.getUint8(i)) + } + } + const temp = SendSerialPortData(gpsFd,arr); + } + + public convertToASCII = (input: string): number[] => { + return input.split('').map(char => char.charCodeAt(0)); + } + + arrayToBuffer(arr: number[]): ArrayBuffer { + const buffer = new ArrayBuffer(arr.length); + const view = new DataView(buffer); + arr.forEach((value, index) => { + view.setUint8(index, value); + }); + return buffer; + } +} \ No newline at end of file diff --git a/entry/src/main/ets/common/rearEndUnitsTool/f&S/UdpByOne.ts b/entry/src/main/ets/common/rearEndUnitsTool/f&S/UdpByOne.ts new file mode 100644 index 00000000..93636b74 --- /dev/null +++ b/entry/src/main/ets/common/rearEndUnitsTool/f&S/UdpByOne.ts @@ -0,0 +1,323 @@ +import socket from '@ohos.net.socket'; +import { PLCGPSData } from '../../../mock/PLCGPSData'; +import FileUtil from '../../../common/utils/File'; +import { GlobalConfig } from '../../../config/index'; + +// import { PLCGPSData } from '../../mock'; + +export default class UdpByOne { + // PLC udp + private PLCUDP: any; + // PLC localIp + private LocalIp: string = '192.168.7.170'; + // PLC localIpPort + private PLCLocalIpPort: number = 31012; + private OppositeIp: string = '192.168.7.124' + // PLC oppositeIpPort + private PLCOppositeIpPort: number = 30012; + // PLC消息 + private PLCMsg: ArrayBuffer; + // GPS udp + private GPSUDP: any; + private GPSTCP: any; + // GPS localIp + // GPS localIpPort + private GPSLocalIpPort: number = 31013; + // GPS oppositeIpPort + private GPSOppositeIpPort: number = 30013; + // GPS消息 + private GPSMsg: any; + + private timer: number; + + //一型机 二型机 + public terType: 1 | 2 + //板卡类型 + public cardType: 0| 1 | 2 + constructor(terType,cardType) { + this.terType = terType; + this.cardType = cardType; + this.init() + } + + async init(){ + const fileUtil = new FileUtil(globalThis.context) + const {terType,cardType} = this + const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); + const result = JSON.parse(data) + this.LocalIp = result.udplocalIp; + this.OppositeIp = result.udpOppositeIp; + this.OppositeIp = result.udpOppositeIp; + + // 初始化UDP + this.PLCUDP = socket.constructUDPSocketInstance(); + // this.PLCUDP.bind(this.PLCLocalIp, this.PLCLocalIpPort); + this.PLCUDP.bind({ + address: this.LocalIp, port: this.PLCLocalIpPort, family: 1 + }); + this.PLCUDP.on("message", (res, remoteInfo) => { + this.PLCMsg = res.message; + }) + + if(terType == 1 && cardType == 1){ + this.GPSTCP = socket.constructTCPSocketInstance(); + await this.GPSTCP.bind({address:this.LocalIp,port:this.GPSLocalIpPort,family: 1}); + try { + await this.GPSTCP.connect({address:{ + address:this.OppositeIp,port:this.GPSOppositeIpPort + }}); + }catch (e) { + console.info('surenjun e=>',JSON.stringify(e)) + } + console.info('surenjun=>','3') + this.GPSTCP.on("message", (res1, remoteInfo) => { + let dataView = new DataView(res1.message) + let str = "" + for (let i = 0; i < dataView?.byteLength; ++i) { + let c = String.fromCharCode(dataView?.getUint8(i)) + if (c !== "\n") {str += c} + } + this.GPSMsg = str; + }) + }else{ + this.GPSUDP = socket.constructUDPSocketInstance(); + // this.GPSUDP.bind(this.GPSLocalIp, this.GPSLocalIpPort); + await this.GPSUDP.bind({ + address: this.LocalIp, port: this.GPSLocalIpPort, family: 1 + }); + this.GPSUDP.on("message", (res1, remoteInfo) => { + let dataView = new DataView(res1.message) + let str = "" + for (let i = 0; i < dataView?.byteLength; ++i) { + let c = String.fromCharCode(dataView?.getUint8(i)) + if (c !== "\n") { + str += c + } + } + this.GPSMsg = str; + }) + } + + + } + // 重新绑定 + public rebind() { + this.PLCUDP.rebind(this.LocalIp, this.PLCLocalIpPort); + this.GPSUDP?.rebind(this.LocalIp, this.GPSLocalIpPort); + this.GPSTCP?.rebind(this.LocalIp, this.GPSLocalIpPort); + } + + // PLC发送消息 + public sendPLCMsg(msg: string) { + this.PLCUDP.send({ + data: '111111', + address: { + address: this.OppositeIp, + port: this.PLCOppositeIpPort, + } + }) + } + + //取消订阅 + public cancelMsg(timer:number){ + clearInterval(timer) + } + + // 处理消息 + public handleMsg() { + let newMessage = PLCGPSData; + const cardType = this.cardType; + console.info('surenjun=> cardType',cardType) + if (this.GPSMsg) { + + let GPGGAMatch = this.GPSMsg.match(/\$GPGGA[^$]*/); + let GPGGAMsgArr = GPGGAMatch ? GPGGAMatch[0]?.split(",").slice(0, 15) : []; + // 使用正则提取$GPRMC消息 + let GPRMCMatch = this.GPSMsg.match(/\$GPRMC[^$]*/); + let GPRMCMsgArr = GPRMCMatch ? GPRMCMatch[0]?.split(",").slice(0, 14) : []; + // 使用正则表达式提取$GPGST消息 + let GPGSTMatch = this.GPSMsg.match(/\$GPGST[^$]*/); + let GPGSTMsgArr = GPGSTMatch ? GPGSTMatch[0]?.split(",").slice(0, 9) : []; + + // 使用正则表达式提取$GPGST消息 + let GNGSTMatch = this.GPSMsg.match(/\$GNGST[^$]*/); + let GNGSTMsgArr = GNGSTMatch ? GNGSTMatch[0]?.split(",").slice(0, 9) : []; + + // 使用正则提取$PTNL消息 + let PTNLMatch = this.GPSMsg.match(/\$PTNL[^$]*/); + let PTNLMsgArr = PTNLMatch ? PTNLMatch[0].split(",")?.slice(0, 14) : []; + // 组合GPS数据 + // 状态83 + newMessage[83] = GPGGAMsgArr[6]; + // 收星数84 + newMessage[84] = GPGGAMsgArr[7]; + // 海拔高85 + newMessage[85] = GPGGAMsgArr[9]; + // 高度差86 + newMessage[86] = GPGGAMsgArr[11]; + // 龄期87 + newMessage[87] = GPGGAMsgArr[13]; + // 维度因子88 + newMessage[88] = GPGSTMsgArr[6] || GNGSTMsgArr[6]; + // 经度因子89 + newMessage[89] = GPGSTMsgArr[7] || GNGSTMsgArr[7]; + // 航向角90 + const hxj = Number(PTNLMsgArr[3]) + newMessage[90] = (cardType == 0 ? hxj : ((hxj + 180 > 360) ?(hxj + 180 - 360): hxj + 180)).toFixed(4) + // newMessage[90] = PTNLMsgArr[3]; + // 俯仰角91 + newMessage[91] = PTNLMsgArr[5]; + // 航向角状态-收星数92 + newMessage[92] = PTNLMsgArr[10] + '-' + (PTNLMsgArr[12] && PTNLMsgArr[12].split('*')[0]); + // 年月日93 RMCMsgArr[9]为ddmmyy 日月年 转换为年月日 + newMessage[93] = + GPRMCMsgArr[9] && (GPRMCMsgArr[9].slice(0, 2) + GPRMCMsgArr[9].slice(2, 4) + GPRMCMsgArr[9].slice(4, 6)); + // 时分秒94 GPGGAMsgArr[1]为021126.00去掉小数点后的时间 + newMessage[94] = GPGGAMsgArr[1] && GPGGAMsgArr[1].replace(".", ""); + // 经度95 + newMessage[95] = GPGGAMsgArr[4]; + // 纬度96 + newMessage[96] = GPGGAMsgArr[2]; + // 速度97 + newMessage[97] = GPRMCMsgArr[7]; + } + if (this.PLCMsg) { + let dataView = new DataView(this.PLCMsg) + let PLCByteArr = [] + for (let i = 0; i < dataView?.byteLength; ++i) { + let c = dataView?.getUint8(i).toString(2).padStart(8, "0") + PLCByteArr.push(c.toString()) + } + if (PLCByteArr.length < 55) { + return newMessage.join(",") + } + // 左方向灯 2 + newMessage[2] = PLCByteArr[6][5]; + // 右方向灯 3 . + newMessage[3] = PLCByteArr[6][4]; + // 喇叭 4 + newMessage[4] = PLCByteArr[8][4]; + // 点火1 5 + newMessage[5] = PLCByteArr[8][7]; + // 点火2 6 + newMessage[6] = PLCByteArr[8][6]; + // 近光灯 7 + newMessage[7] = PLCByteArr[6][7]; + // 远光灯 8 + newMessage[8] = PLCByteArr[6][6]; + // 示廓灯 9 + newMessage[9] = PLCByteArr[6][2]; + // 雾灯 10 + // 雨刮器 11 + newMessage[11] = PLCByteArr[8][5]; + // 脚刹 12 + newMessage[12] = PLCByteArr[7][5]; + // 手刹 13 + newMessage[13] = PLCByteArr[7][4]; + // 主驾驶门 14 + newMessage[14] = PLCByteArr[7][7]; + // NC 15 + // TODO + // SA15 16 + // TODO + // 离合 17 + newMessage[17] = PLCByteArr[7][6]; + // 副刹车 18 + newMessage[18] = PLCByteArr[7][3]; + // 安全带 19 + newMessage[19] = PLCByteArr[7][0]; + // 双跳灯 20 + newMessage[20] = PLCByteArr[6][3]; + // 其他门 21 + // TODO + // 转速过高 22 + newMessage[22] = PLCByteArr[9][0]; + // 车速 23 + newMessage[23] = parseInt(PLCByteArr[11], 2)+''; + // 累计脉冲 24 + let Data25 = parseInt(PLCByteArr[25], 2); + let Data26 = parseInt(PLCByteArr[26], 2); + let Data27 = parseInt(PLCByteArr[27], 2); + let Data28 = parseInt(PLCByteArr[28], 2); + newMessage[24] = ((Data25 << 24) + (Data26 << 16) + (Data27 << 8) + Data28).toString(); + // 发动机转速 25 + let Data29 = parseInt(PLCByteArr[29], 2); + let Data30 = parseInt(PLCByteArr[30], 2); + let Data31 = parseInt(PLCByteArr[31], 2); + let Data32 = parseInt(PLCByteArr[32], 2); + newMessage[25] = ((Data29 << 24) + (Data30 << 16) + (Data31 << 8) + Data32).toString(); + // 熄火次数 26 + newMessage[26] = parseInt(PLCByteArr[33], 2) + ''; + + // 方向盘角度 27 + // TODO 档位 磁档位为外接信号 + newMessage[28] = (globalThis.chuankoMsg == '0' || globalThis.chuankoMsg == '' ||globalThis.chuankoMsg == undefined)?(parseInt(PLCByteArr[13], 2) + ''): globalThis.chuankoMsg; + + if(this.terType == 1){ + // 超声波1 + newMessage[29] = (PLCByteArr[4][1] > 0 ? '300' : '1200') + // 超声波2 + newMessage[30] = (PLCByteArr[4][0] > 0 ? '300': '1200' ) + } + + if(this.terType == 2){ + newMessage[29] = (parseInt(PLCByteArr[52], 2) > 10) ? '1200' : '300' + newMessage[30] = (parseInt(PLCByteArr[54], 2) > 10) ? '1200': '300' + } + + //TODO 超声波3 临时写死 + newMessage[31] = '1200' + //TODO 超声波4 临时写死 + newMessage[32] = '1200' + // 触摸1 33 + // 触摸2 34 + // 触摸3 35 + // SCIO 36 + // SC1A_C 37 + // SC1B_C 38 + // SC2A_C 39 + // SC2B_C 40 + // SC3A_C 41 + // SC3B_C 42 + // SC4A_C 43 + // SC4B_C 44 + // SC5A_C 45 + // SC5B_C 46 + // SC6A_C 47 + // SC6B_C 48 + // 发送次数 49 + // 方向盘类型 50 + // 汽车类型 51 + // 接口心跳 52 + // 本机IP 53 + // 固件版本 54 + // 按键数值 55 + // GPS板卡类型 56 + // GPS板卡软件版本 57 + // 改正数次数/改正数大小 58 + // GPS数据次数/数据长度 59 + // GPS错误次数 60 + // 已工作时长/设定的工作时长 61 + // 改正数数据长度*数据长度-基准站RTCM改正数类型 62 + } + return newMessage.map(item => { + return item === undefined?'':item + }).join(",") + } + + // PLC接收消息 + public receivePLCMsg() { + this.PLCUDP.on("message", (message, remoteInfo) => { + console.log(`PLC receive message from ${remoteInfo.address}:${remoteInfo.port} : ${message}`); + this.PLCMsg = message; + }) + } + + // GPS接收消息 + public receiveGPSMsg() { + this.GPSUDP.on("message", (message, remoteInfo) => { + console.log(`GPS receive message from ${remoteInfo.address}:${remoteInfo.port} : ${message}`); + this.GPSMsg = message; + }) + } +} \ No newline at end of file diff --git a/entry/src/main/ets/common/rearEndUnitsTool/index.ts b/entry/src/main/ets/common/rearEndUnitsTool/index.ts new file mode 100644 index 00000000..707447dc --- /dev/null +++ b/entry/src/main/ets/common/rearEndUnitsTool/index.ts @@ -0,0 +1,157 @@ +import FileUtil from '../utils/File'; +import { GlobalConfig } from '../../config'; +import common from '@ohos.app.ability.common'; +import UdpByOne from './f&S/UdpByOne'; +import AIO from './aio/aioClass' +import GpsTcpClient from '../utils/GpsTcpClient' + +export default class RearEndUnitsTool { + //一型机 二型机 三型机 一体机 + public terType: 0 | 1 | 2 | 3 = 2; + //C1板卡 B4板卡 + public cardType: 0 | 1; + public timer: number = 0 + public diffTimer: number = 0 + private UdpByOneClass: UdpByOne + public AioClass: AIO + public GpsTcpClientClass: GpsTcpClient + private diffData: number[] + + constructor(context: common.UIAbilityContext) { + this.getTerType(context) + } + + public receiveMsg = (callBack)=> { + const terType = this.terType; + const cardType = this.cardType; + //TODO 临时处理关闭消息接收 + this.cancelMsg() + + switch (terType) { + //一型机 + case 0: { + const udpClass = this.getFUdp({ + terType: 1, + cardType, + }); + + this.timer = setInterval(() => { + const message = udpClass.handleMsg() + callBack && callBack(message) + }, 200) + } + break; + + //二型机 + case 1: { + const udpClass = this.getFUdp({ + terType: 2, + cardType + }) + this.timer = setInterval(() => { + const message = udpClass.handleMsg() + callBack && callBack(message) + }, 200) + break; + } + break; + + //三型机 + case 2: + // this.timer = setInterval(() => { + // callBack && callBack(message) + // }, 200) + // break; + + //一体机 + case 3: + const aioClass = this.getAio() + this.timer = setInterval(() => { + const message = aioClass.handleMsg() + callBack && callBack(message) + }, 200) + + this.diffTimer = setInterval(()=>{ + aioClass.sendDiffCorrections(this.diffData) + },1000) + default: + break + } + + return this.timer + } + + //取消订阅 + public cancelMsg() { + clearInterval(this.timer) + clearInterval(this.diffTimer) + } + + //获取后置机设备类型 + private async getTerType(context) { + const fileUtil = new FileUtil(context) + const config = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); + const result = JSON.parse(config || '{}') + //默认设置为三代机 + this.terType = result.terType + this.cardType = result.cardType + return this.terType + } + + //获取一型机&二型机单例 + private getFUdp({terType,cardType}) { + if (!this.UdpByOneClass) { + this.UdpByOneClass = new UdpByOne(terType,cardType); + } + return this.UdpByOneClass; + } + + // 获取一体机 + private getAio =()=> { + if (!this.AioClass) { + this.AioClass = new AIO() + } + return this.AioClass; + } + + //获取转发gps差分的tcp + private getGpsTcp =()=>{ + if(!this.GpsTcpClientClass){ + this.GpsTcpClientClass = new GpsTcpClient() + } + return this.GpsTcpClientClass + } + + // 转发差分改正数 + public sendDiffCorrections = (message) => { + const type = this.terType + const cardType = this.cardType + //差分改正数截取前5位 + let dataView = new DataView(message) + const Arraybuffer = message.slice(5, dataView?.byteLength); + + switch (type){ + //一型机 + case 0: + //天宝类型板卡 + if(cardType === 1){ + globalThis.udpClient?.sendMsg(Arraybuffer);break + }else{ + const GpsTcpClientClass = this.getGpsTcp() + GpsTcpClientClass.sendGpsMsg(Arraybuffer);break + } + + //二型机 + case 1: globalThis.udpClient?.sendMsg(Arraybuffer);break + + //三型机 + case 2: globalThis.udpClient?.sendMsg(Arraybuffer);break + + //一体机的差分不需要截取 + case 3: this.diffData = message;break + } + + } + + public send +} \ No newline at end of file diff --git a/entry/src/main/ets/common/service/indexService.ts b/entry/src/main/ets/common/service/indexService.ts index 00b0c3eb..5934d8d1 100644 --- a/entry/src/main/ets/common/service/indexService.ts +++ b/entry/src/main/ets/common/service/indexService.ts @@ -1,10 +1,12 @@ // @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 request from '@ohos.request' +import Prompt from '@system.prompt'; import { delSyncTable, @@ -16,7 +18,7 @@ import { import { GlobalConfig } from '../../config/index' import testNapi from '@ohos.hiserialsdk' import fs from '@ohos.file.fs'; - +import zlib from '@ohos.zlib'; let num = 0 async function getliushuiNum(data) { @@ -39,6 +41,152 @@ async function getliushuiNum(data) { } +const TAG = '[UPLOAD]' +export async function uploadLogFile() { + + if(globalThis.upload){ + return + } + globalThis.upload = true + Prompt.showToast({ + message: '正在上传考车日志,请耐心等待...', + duration: 3000 + }); + const filename = await getCopyFiles() + const filePath = globalThis.context.cacheDir + '/' + filename + let stat = fs.statSync(filePath) + console.log(TAG,'上传压缩包文件大小:' + (Math.ceil(stat.size / 1024 / 1024)) + 'M') + // const currentFilename = globalThis.carInfo.plateNo + '_' + await getCurrentTime(1)+ '_log.zip'; + // console.log(TAG,'upload log currentFilename=>' ,currentFilename )xxx + let uploadConfig: request.UploadConfig = { + header: { 'Accept': '*/*', 'Content-Type': 'multipart/form-data' }, + url: `${globalThis.host}/der2/services/upload?fileName=${filename}`, + files: [{ filename, name: filename, uri: `internal://cache/${filename}`, type: "zip" }], + data: [{ name: filename, value: filename }], + } + request.uploadFile(globalThis.context, uploadConfig).then(data =>{ + let uploadTask: request.UploadTask = data; + console.log(TAG,'start upload') + const callback = (size, tot) => { + console.log(TAG + '文件上传中', "进度" + size + '/' + tot) + } + //on("progress") 存在bug + let timer = setInterval(()=>{ + uploadTask.on("progress", callback) + uploadTask.off('progress', callback) + },1000) + uploadTask.on('complete', () => { + console.log(TAG + '文件上传完成') + clearInterval(timer) + globalThis.upload = false + fs.rmdirSync(filePath); + Prompt.showToast({ + message: '考车日志上传成功', + duration: 3000 + }); + }) + uploadTask.on("fail", (taskInfo) => { + console.log(TAG + '文件上传失败' ,JSON.stringify(taskInfo)) + Prompt.showToast({ + message: '考车日志上传失败', + duration: 3000 + }); + clearInterval(timer) + globalThis.upload = false + }) + uploadTask.on("headerReceive", header => { + console.log(TAG + 'headerReceive=>',JSON.stringify(header)) + }) + }) + +} + + +// 将要上传的文件拷贝到缓存目录并压缩 +async function getCopyFiles() { + const absolutePath = '/mnt/hmdfs/100/account/device_view/local/files/duolun/logs' + const tempPath = globalThis.context.cacheDir + '/temp'; + + if (!fs.accessSync(tempPath)) { + fs.mkdirSync(tempPath) + } + + let listFileOption = { + recursion: true, + listNum: 0, + filter: {suffix: [".txt"],} + }; + const list = fs.listFileSync(absolutePath,listFileOption); + console.log(TAG,'开始备份log文件,数量:' + list.length) + list.forEach((folder=>{ + const folders = folder.split('/'); + let path = tempPath + folders.forEach(((item,index)=>{ + if(index !== 0 && index !== folders.length-1){ + path += `/${item}`; + if (!fs.accessSync(path)) { + fs.mkdirSync(path); + } + } + })) + fs.copyFileSync(absolutePath + folder, tempPath + folder) + })) + console.log(TAG,'log文件备份完成') + + const time = await getCurrentTime(); + const nowDate = time.split(' ')[0].split('-').join('') + const filenames = await fs.listFile('/data/log/hilog'); + 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]) + } + } + } + + console.log(TAG,'开始压缩文件') + const currentFilename = globalThis.carInfo.carNo + '_' + await getCurrentTime(1)+ '.zip'; + await compressFile(tempPath, globalThis.context.cacheDir + '/' + currentFilename) + console.log(TAG,'压缩完成') + fs.rmdirSync(globalThis.context.cacheDir + '/temp'); + return currentFilename +} + + +// 打包当天日志文件 +async function compressCurrentLogs() { + const time = await getCurrentTime(); + const nowDate = time.split(' ')[0].split('-').join('') + const filenames = await fs.listFile('/data/storage/100/local/files/duolun/logs'); + + let options: zlib.Options = { + level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION, + memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT, + strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY + }; + + 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]) + } + } + } + console.log('upload log copy files success') +} + +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 deleteAllFIleLog(path) { let options = { "recursion": false, @@ -170,12 +318,11 @@ export async function getSingleCenterTable(param) { return new Promise((resolve, reject) => { console.log('teststet0') upDataZhongxinginitialization(param).then((result) => { - console.log('kkkkkkkkkkk', result) - if (result) { + if (result === true) { resolve(true) } else { console.log('联网更新失败,请检查网络后重新更新') - resolve(false) + resolve(result) } }).catch((error) => { resolve(false) diff --git a/entry/src/main/ets/common/service/initable.ts b/entry/src/main/ets/common/service/initable.ts index 3ff13db4..def04b15 100644 --- a/entry/src/main/ets/common/service/initable.ts +++ b/entry/src/main/ets/common/service/initable.ts @@ -96,6 +96,9 @@ export async function initTable() { export function sqlInsertCommonFn(tableName, resultArr, delFlag = true) { return new Promise((resolve, reject) => { DB.clearTable(tableName).then((res) => { + if(!resultArr?.length){ + return + } let INSERT_SQL = "INSERT INTO " + tableName + " (" + map[tableName].ACCOUNT_TABLE.columns.toString() + ") VALUES " @@ -455,7 +458,7 @@ export async function upDataZhongxinginitialization(param) { resolve(true) }).catch((Error) => { console.log("init table5", JSON.stringify(Error)) - resolve(false) + resolve(Error.initializationRsp.head) }) } catch (error) { console.log("init table6", JSON.stringify(error)) diff --git a/entry/src/main/ets/common/service/videoService.ts b/entry/src/main/ets/common/service/videoService.ts index 6884c912..779b0ebb 100644 --- a/entry/src/main/ets/common/service/videoService.ts +++ b/entry/src/main/ets/common/service/videoService.ts @@ -50,7 +50,7 @@ export async function startRecordVideo(param, td, context, dir, path?, index?) { if (!path) { fileName = `${date}_movie_record${num}.mp4` } else { - fileName = `${date}_${path}_${index || num}.mp4` + fileName = `${date}_${path}_${index || num}_${num}.mp4` } // @ts-ignore diff --git a/entry/src/main/ets/common/utils/File.ts b/entry/src/main/ets/common/utils/File.ts index 73780f38..dd1941ee 100644 --- a/entry/src/main/ets/common/utils/File.ts +++ b/entry/src/main/ets/common/utils/File.ts @@ -1,190 +1,137 @@ import Want from '@ohos.app.ability.Want' import promptAction from '@ohos.promptAction' -import fileAccess from '@ohos.file.fileAccess' import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl' import common from '@ohos.app.ability.common' import fs from '@ohos.file.fs' const LOGTAG = 'LOGTAG' -export default class FileUtil{ - private context: common.UIAbilityContext - private wantInfos: Want[] - private fileAccessHelper: fileAccess.FileAccessHelper - - //后续文件路径待替换 - private absolutePath = '/mnt/hmdfs/100/account/device_view/local/files/duolun' - - public destFile:string - public filePathFdObj:Object = {} - - constructor(wantInfos) { - const {requestPermission} = this; - this.wantInfos = wantInfos; - requestPermission(); - fs.mkdir(this.absolutePath) - } - - /* - * @desc 校验文件夹,文件夹不存在会创建,支持嵌套 - * - */ - public initFolder = async (folderPath:string) => { - const {absolutePath} = this; - const folderList = folderPath.split('/').filter(folderName => folderName !== ''); - - let path = absolutePath - folderList.forEach((folderName=>{ - path += `/${folderName}`; - try { - const isExit = fs.accessSync(path); - if(!isExit){ - fs.mkdirSync(path) - } - } catch (e) { - console.info('初始化文件夹失败',path) - promptAction.showToast({ - message:`初始化文件夹失败`+ folderPath + JSON.stringify(e), - duration:4000, - }) - } - })); - return path; - } +export default class FileUtil { + public destFile: string + public filePathFdObj: Object = {} /* * @desc 创建并覆盖文件 * */ - public addFile = async (filePath:string,content:string,type?:string)=>{ - const { READ_WRITE,CREATE,APPEND }= fs.OpenMode + public addFile = async (filePath: string, content: string, type?: string) => { + const { READ_WRITE,CREATE,APPEND } = fs.OpenMode const isExit = fs.accessSync(filePath); //文件存在先删除 - if(isExit){ + if (isExit) { fs.unlinkSync(filePath); } try { - let file = fs.openSync(filePath, READ_WRITE | CREATE); + let file = fs.openSync(filePath, READ_WRITE | CREATE); //追加写入文件 - fs.writeSync(file.fd,content) + fs.writeSync(file.fd, content) fs.closeSync(file) - console.error(LOGTAG,'写入文件成功') + console.error(LOGTAG, '写入文件成功') return true - }catch (e){ + } catch (e) { promptAction.showToast({ - message:`addFile文件失败`+ filePath +JSON.stringify(e), - duration:4000, + message: `addFile文件失败` + filePath + JSON.stringify(e), + duration: 4000, }) - console.error(LOGTAG,'写入失败',JSON.stringify(e)) + console.error(LOGTAG, '写入失败', JSON.stringify(e)) } } /* * @desc 创建或者编辑文件 * */ - public editFile = async (filePath:string,content:string,fd?:number)=>{ + public editFile = async (filePath: string, content: string, fd?: number) => { const {filePathFdObj} = this; - const { READ_WRITE,CREATE,APPEND }= fs.OpenMode - const newStr = content + '\n' + const { READ_WRITE,CREATE,APPEND } = fs.OpenMode + const newStr = content + '\n' const thisFile = filePathFdObj[filePath]; try { - if(thisFile){ - fs.writeSync(thisFile.fd,newStr) + if (thisFile) { + fs.writeSync(thisFile.fd, newStr) return fd; - }else{ - let file = fs.openSync(filePath, READ_WRITE | APPEND |CREATE); - fs.writeSync(file.fd,newStr) + } else { + let file = fs.openSync(filePath, READ_WRITE | APPEND | CREATE); + fs.writeSync(file.fd, newStr) this.filePathFdObj[filePath] = file return file.fd } } catch (e) { promptAction.showToast({ - message:`editFile文件失败`+ filePath +JSON.stringify(e), - duration:4000, + message: `editFile文件失败` + filePath + JSON.stringify(e), + duration: 4000, }) - console.error(LOGTAG,JSON.stringify(e)) + console.error(LOGTAG, JSON.stringify(e)) } } - /* * @desc 关闭文件 * */ - public closeFile = async (filePath:string)=>{ + public closeFile = async (filePath: string) => { const {filePathFdObj} = this; const thisFile = filePathFdObj[filePath]; - if(thisFile){ + if (thisFile) { fs.closeSync(thisFile); - console.info(LOGTAG,filePath + '文件关闭成功') + console.info(LOGTAG, filePath + '文件关闭成功') } } - /* * @desc 读取文件 * **/ - public readFile = async (filePath:string) => { - try{ - console.log('strrr',filePath) + public readFile = async (filePath: string) => { + try { + console.log('strrr', filePath) const str = await fs.readText(filePath); return str - }catch (e){ + } catch (e) { promptAction.showToast({ - message:`读取文件失败`+ filePath +JSON.stringify(e), - duration:4000, + message: `读取文件失败` + filePath + JSON.stringify(e), + duration: 4000, }) - console.log('readFile文件失败'+ filePath +JSON.stringify(e)) + console.log('readFile文件失败' + filePath + JSON.stringify(e)) return '' } } - /* * @desc获取系统目录里的文件列表 */ - public getDeviceList = async (folderPath?:string)=>{ + public getDeviceList = async (folderPath?: string) => { const {absolutePath,getFilePathList} = this; - return getFilePathList(`${absolutePath}/${folderPath}`,false) + return getFilePathList(`${absolutePath}/${folderPath}`, false) }; + private context: common.UIAbilityContext + private wantInfos: Want[] + private fileAccessHelper: any + //后续文件路径待替换 + private absolutePath = '/mnt/hmdfs/100/account/device_view/local/files/duolun' + private getFilePathList = async (filePath: string, isSdcard: boolean) => { + let fileName = [], sdCardFileName = []; - // 删除文件夹或者文件 - /* - * @desc 删除文件夹或者文件 - * @param{{type}} 1:文件夹 2:文件 3:自定义目录下文件 - **/ - - public deleteF = async (path:string,type: 1 | 2 | 3) => { - const {getFilePathList,absolutePath} = this - if(type === 1){ - const fileList = await getFilePathList(`${absolutePath}/${path}`,false); - fileList.forEach(filePath =>{ - fs.unlinkSync(`${absolutePath}/${path}/${filePath}`); - }) - fs.rmdirSync(`${absolutePath}/${path}`); - return true + try { + const filenames = await fs.listFile(filePath); + for (let i = 0; i < filenames.length; i++) { + console.log(LOGTAG, `目录:${filePath}的子文件:${filenames[i]}`); + if (isSdcard) { + sdCardFileName.push(filenames[i]) + } else { + fileName.push(filenames[i]) + } + } + return isSdcard ? sdCardFileName : fileName + } catch (e) { + console.error(LOGTAG, JSON.stringify(e)); } - if(type === 2){ - fs.unlinkSync(`${absolutePath}/${path}`); - return true - } - if(type === 3){ - fs.unlinkSync(`${path}`); - return true - } } - - // 获取系统文件绝对路径 - public getAbsolutePath = () =>{ - const {absolutePath} = this; - return absolutePath - } - // 检索文件列表 public getSdCardPathList = async () => { + //@ts-ignore this.wantInfos = await fileAccess.getFileAccessAbilityInfo(); const {wantInfos,context} = this; - const fileAccessHelper = fileAccess.createFileAccessHelper(this.context,this.wantInfos); + //@ts-ignore + const fileAccessHelper = fileAccess.createFileAccessHelper(this.context, this.wantInfos); this.fileAccessHelper = fileAccessHelper; let isDone = false; @@ -200,52 +147,29 @@ export default class FileUtil{ if (!isDone) { let deviceType = rootInfo.value.deviceType; let displayName = rootInfo.value.displayName; - let uri:string = rootInfo.value.uri; + let uri: string = rootInfo.value.uri; let deviceFlags = rootInfo.value.deviceFlags; - console.error(LOGTAG,`设备类型:${deviceType},设备名称:${displayName},设备根目录Uri:${uri},设备支持的能力:${deviceFlags}`); + console.error(LOGTAG, `设备类型:${deviceType},设备名称:${displayName},设备根目录Uri:${uri},设备支持的能力:${deviceFlags}`); - if(uri.indexOf('/mnt/external/')>0){ + if (uri.indexOf('/mnt/external/') > 0) { // if('vol-8-1' ==displayName){ - this.destFile = uri.split('ExternalFileManager')[1]+'/' - console.error(LOGTAG,`外置存储路径:`+this.destFile); - this.getFilePathList(this.destFile,true) + this.destFile = uri.split('ExternalFileManager')[1] + '/' + console.error(LOGTAG, `外置存储路径:` + this.destFile); + this.getFilePathList(this.destFile, true) } } } } catch (error) { - console.error(LOGTAG,"getRoots failed, errCode:" + error.code + ", errMessage:" + error.message); + console.error(LOGTAG, "getRoots failed, errCode:" + error.code + ", errMessage:" + error.message); } } - public getFileContent = (filePath:string) => { - const {absolutePath} = this; - const { READ_WRITE }= fs.OpenMode - const path = `${absolutePath}/${filePath}` - const str = fs.readTextSync(path); - return str - } - - private getFilePathList = async (filePath:string,isSdcard:boolean) => { - let fileName = [],sdCardFileName = []; - - try { - const filenames = await fs.listFile(filePath); - for (let i = 0; i < filenames.length; i++) { - console.error(LOGTAG,`目录:${filePath}的子文件:${filenames[i]}`); - if(isSdcard){ - sdCardFileName.push(filenames[i]) - }else{ - fileName.push(filenames[i]) - } - } - return isSdcard ? sdCardFileName : fileName - }catch (e){ - console.error(LOGTAG,JSON.stringify(e)); - } - - } - + // 删除文件夹或者文件 + /* + * @desc 删除文件夹或者文件 + * @param{{type}} 1:文件夹 2:文件 3:自定义目录下文件 + **/ // 文件系统初始化 private requestPermission = async () => { const {context,absolutePath} = this; @@ -253,19 +177,88 @@ export default class FileUtil{ 'ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA' ]; + // @ts-ignore this.wantInfos = await fileAccess.getFileAccessAbilityInfo(); let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager() - atManager.requestPermissionsFromUser(context, permissions , async (code, result) => { + atManager.requestPermissionsFromUser(context, permissions, async (code, result) => { const permissionRequest = result.authResults[0] - if(permissionRequest == -1){ + if (permissionRequest == -1) { promptAction.showToast({ message: "请先授权", - duration:3000, + duration: 3000, }) return } }) } + constructor(wantInfos) { + const {requestPermission} = this; + this.wantInfos = wantInfos; + requestPermission(); + fs.mkdir(this.absolutePath) + } + /* + * @desc 校验文件夹,文件夹不存在会创建,支持嵌套 + * + */ + public initFolder = async (folderPath: string) => { + const {absolutePath} = this; + const folderList = folderPath.split('/').filter(folderName => folderName !== ''); + + let path = absolutePath + folderList.forEach((folderName => { + path += `/${folderName}`; + try { + const isExit = fs.accessSync(path); + if (!isExit) { + fs.mkdirSync(path) + } + } catch (e) { + console.info('初始化文件夹失败', path) + promptAction.showToast({ + message: `初始化文件夹失败` + folderPath + JSON.stringify(e), + duration: 4000, + }) + } + })); + return path; + } + + public deleteF = async (path: string, type: 1 | 2 | 3) => { + const {getFilePathList,absolutePath} = this + if (type === 1) { + const fileList = await getFilePathList(`${absolutePath}/${path}`, false); + fileList.forEach(filePath => { + console.info(LOGTAG+'开始删除文件', `${absolutePath}/${path}/${filePath}`) + fs.unlinkSync(`${absolutePath}/${path}/${filePath}`); + }) + fs.rmdirSync(`${absolutePath}/${path}`); + return true + } + + if (type === 2) { + fs.unlinkSync(`${absolutePath}/${path}`); + return true + } + if (type === 3) { + fs.unlinkSync(`${path}`); + return true + } + } + + // 获取系统文件绝对路径 + public getAbsolutePath = () => { + const {absolutePath} = this; + return absolutePath + } + + public getFileContent = (filePath: string) => { + const {absolutePath} = this; + const { READ_WRITE } = fs.OpenMode + const path = `${absolutePath}/${filePath}` + const str = fs.readTextSync(path); + return str + } } diff --git a/entry/src/main/ets/common/utils/GetDistance.ts b/entry/src/main/ets/common/utils/GetDistance.ts index 9ba9090d..cf94b566 100644 --- a/entry/src/main/ets/common/utils/GetDistance.ts +++ b/entry/src/main/ets/common/utils/GetDistance.ts @@ -13,6 +13,7 @@ export default class GetDistance { public totalTime:number public date: string public fd: number + public timeInterval:number constructor(context) { const fileUtil = new FileUtil(context) @@ -24,7 +25,6 @@ export default class GetDistance { const {fileUtil} = this const time = await getCurrentTime() const folderPath = await fileUtil.initFolder(`/车辆行驶距离统计`); - console.info('surenjun folderPath=>' ,folderPath); const date = time.split(' ')[0].split('-').join('_') const timeStr = time.split(' ')[1] this.timeStr = timeStr @@ -40,16 +40,12 @@ export default class GetDistance { // 过程文件数据 public setTimeData = async (str:number) => { - const {fileUtil,folderPath,timeStr,date,totalDistance} = this; - console.log('folderPath',folderPath) - const content = await fileUtil.readFile(`${folderPath}/${date}.txt`) || ''; - const contentArr = content.split('\n').filter(item => item) - console.info('surenjun contentArr',JSON.stringify(contentArr)) - this.totalDistance += (str * 1 > 200 ? 200 : str*1) + // const {fileUtil,folderPath,timeStr,date,totalDistance} = this; + // const content = await fileUtil.readFile(`${folderPath}/${date}.txt`) || ''; + // const contentArr = content.split('\n').filter(item => item) + // this.totalDistance += (str * 1 > 200 ? 200 : str*1) this.totalTime += 1; - contentArr[contentArr.length - 1] = `程序启动时间:${timeStr} 累计行驶距离:${(this.totalDistance).toFixed(2)}m 累计运行时常:${Math.ceil(this.totalTime/60)}min`+ '\n' - console.info('surenjun',contentArr.join('\n')) - console.log('folderPath',folderPath,date) + // contentArr[contentArr.length - 1] = `程序启动时间:${timeStr} 累计行驶距离:${(this.totalDistance).toFixed(2)}m 累计运行时常:${Math.ceil(this.totalTime/60)}min`+ '\n' this.uploadData() // await fileUtil.addFile( @@ -59,18 +55,18 @@ export default class GetDistance { //上传行驶里程数据 uploadData = async () => { - setInterval(()=>{ - const { carId } = globalThis.carInfo; - const {date,timeStr,totalDistance}= this; - return - //"carid":"1001","startTime":"2024-08-24 08:09:01","time":"111233", "mileage":"1222" - uploadHarmonyLiCheng({ - carid:carId, - startTime:`${date.split('_').join('-')} ${timeStr}`, - time:timeStr, - mileage:totalDistance - }) - },5000) + clearInterval(this.timeInterval) + const { carId } = globalThis.carInfo; + const {date,totalTime,totalDistance,timeStr}= this; + + // return + //"carid":"1001","startTime":"2024-08-24 08:09:01","time":"111233", "mileage":"1222" + uploadHarmonyLiCheng({ + carid:carId, + startTime:`${date.split('_').join('-')} ${timeStr}`, + time:totalTime, + mileage:totalDistance + }) } } diff --git a/entry/src/main/ets/common/utils/GlobalTcp.ts b/entry/src/main/ets/common/utils/GlobalTcp.ts index 04485318..eec03438 100644 --- a/entry/src/main/ets/common/utils/GlobalTcp.ts +++ b/entry/src/main/ets/common/utils/GlobalTcp.ts @@ -3,16 +3,23 @@ import { getSyncData } from '../service/initable'; import hilog from '@ohos.hilog'; import FileUtil from '../../common/utils/File' import { GlobalConfig } from '../../config/index' + export async function getTCP(flag=false) { globalThis.getCloseTcp=true const fileUtil = new FileUtil(globalThis.context) const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); + if (data === '' || data === undefined) { globalThis.TcpClient = {} globalThis.TcpClient.onMessage = () => { } }else{ - const result=JSON.parse(data) + const result = JSON.parse(data) + const netOpen = result.netOpen + //是否开启网络差分 + if(netOpen != 1){ + return + } if (globalThis.TcpClient && globalThis.TcpClient.closeTcp&&!flag) { globalThis.TcpClient.closeTcp(async () => { // const tcpClient: TcpClient =new TcpClient(result[0].tcplocalIp, result[0].tcplocalIpPort,result[0].tcpOppositeIp,result[0].tcpOppositePort) @@ -42,9 +49,7 @@ export async function getTCP(flag=false) { await globalThis.TcpClient.onMessage((val) => { setTimeout(() => { if (val) { - // const msg=val.substring(5,val.length-1) - console.log('socketTag[PLC.UdpClient] status:', globalThis.udpClient.getStatus()) - globalThis.udpClient?.sendMsg(val) + globalThis.retClass?.sendDiffCorrections(val) } }, 1000) @@ -77,76 +82,14 @@ export async function getTCP(flag=false) { await globalThis.TcpClient.onMessage((val) => { setTimeout(() => { if (val && globalThis.udpClient?.sendMsg) { - globalThis.udpClient?.sendMsg(val) + globalThis.retClass?.sendDiffCorrections(val) } }, 1000) }) } } - return - getSyncData('IpConfigTable').then(async (result: Array) => { - console.log('result222', JSON.stringify(result)) - if (result.length) { - if (globalThis.TcpClient && globalThis.TcpClient.closeTcp) { - globalThis.TcpClient.closeTcp(async () => { - // const tcpClient: TcpClient =new TcpClient(result[0].tcplocalIp, result[0].tcplocalIpPort,result[0].tcpOppositeIp,result[0].tcpOppositePort) - // globalThis.TcpClient = tcpClient - setTimeout(async () => { - await globalThis.TcpClient.rebindTcp(result[0].tcplocalIp, result[0].tcplocalIpPort, result[0].tcpOppositeIp, result[0].tcpOppositePort) - await globalThis.TcpClient.connectTcp() - await globalThis.TcpClient.sendMsg('1002') //1002 - globalThis.TcpClient.onError((val) => { - setTimeout(() => { - getTCP() - }, 1000) - }) - await globalThis.TcpClient.onMessage((val) => { - setTimeout(() => { - globalThis.TcpClient.sendMsg('1002') //1002 - if (val) { - // const msg=val.substring(5,val.length-1) - console.log('socketTag[PLC.UdpClient] status:', globalThis.udpClient.getStatus()) - globalThis.udpClient?.sendMsg(val) - } - }, 1000) - - }) - }, 2000) - }) - - } - else { - const tcpClient: TcpClient = new TcpClient(result[0].tcplocalIp, result[0].tcplocalIpPort, result[0].tcpOppositeIp, result[0].tcpOppositePort) - globalThis.TcpClient = tcpClient - await globalThis.TcpClient.bindTcp() - await globalThis.TcpClient.connectTcp() - await globalThis.TcpClient.sendMsg('1002') //1002 - globalThis.TcpClient.onError((val) => { - setTimeout(() => { - getTCP() - }, 1000) - }) - await globalThis.TcpClient.onMessage((val) => { - hilog.info(0x0000, 'testTag', "valvalval2" + JSON.stringify(val)); - setTimeout(() => { - globalThis.TcpClient.sendMsg('1002') //1002 - if (val && globalThis.udpClient?.sendMsg) { - globalThis.udpClient?.sendMsg(val) - } - }, 1000) - - }) - } - // globalThis.udpClient = new UdpClient(result[0].localIp, result[0].localIpPort,result[0].oppositeIp,result[0].oppositeIpPort) - - } else { - globalThis.TcpClient = {} - globalThis.TcpClient.onMessage = () => { - } - } - }) } diff --git a/entry/src/main/ets/common/utils/GlobalUdp.ts b/entry/src/main/ets/common/utils/GlobalUdp.ts index ba599236..78e36675 100644 --- a/entry/src/main/ets/common/utils/GlobalUdp.ts +++ b/entry/src/main/ets/common/utils/GlobalUdp.ts @@ -1,41 +1,41 @@ //import UdpClient from './UdpClient'; import UdpClientByCenter from './UdpClientByCenter'; -import { getSyncData } from '../service/initable' -import { getChuankouFn } from '../../common/service/indexService' -import FileUtil from '../../common/utils/File' -import { GlobalConfig } from '../../config/index' -import {Array2Byte,fillZero,string2Bytes}from './tools' -import emitter from '@ohos.events.emitter'; +import { getSyncData } from '../service/initable'; +import { getChuankouFn,uploadLogFile} from '../../common/service/indexService'; +import FileUtil from '../../common/utils/File'; +import { GlobalConfig } from '../../config/index'; +import { Array2Byte, string2Bytes } from './tools'; 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 `); globalThis.udpClient.closeUdp(() => { setTimeout(() => { - globalThis.udpClient.rebindUdp(result.udplocalIp, result.udplocalIpPort, result.udpOppositeIp, result.udpOppositeIpPort) + 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}`) @@ -44,25 +44,23 @@ export async function getUDP(context,errorFlag?) { }, 1000) }) - } - else { + } else { // 未绑定 console.log(` getUDP has no udclent and bind `); - console.log('ttttttdata',JSON.stringify(result)) - const udpClient: UdpClientByCenter = new UdpClientByCenter(result.udplocalIp, result.udplocalIpPort, result.udpOppositeIp, result.udpOppositeIpPort) + 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(()=>{ - 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() @@ -79,14 +77,15 @@ export async function getUDP(context,errorFlag?) { console.log(` getUDP has udclent close and rebind `); globalThis.udpClient.closeUdp(() => { setTimeout(() => { - globalThis.udpClient.rebindUdp(result[0].udplocalIp, result[0].udplocalIpPort, result[0].udpOppositeIp, result[0].udpOppositeIpPort) + 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}`) @@ -95,24 +94,25 @@ export async function getUDP(context,errorFlag?) { }, 1000) }) - } - else { + } else { // 未绑定 console.log(` getUDP has no udclent and bind `); - const udpClient: UdpClientByCenter = new UdpClientByCenter(result[0].udplocalIp, result[0].udplocalIpPort, result[0].udpOppositeIp, result[0].udpOppositeIpPort) + const udpClient: UdpClientByCenter = + new UdpClientByCenter(result[0].udplocalIp, result[0].udplocalIpPort, result[0].udpOppositeIp, + result[0].udpOppositeIpPort) udpClient.bindUdp() udpClient.sendMsg('111') 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,61 +140,73 @@ 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.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 } }) }, 1000) }) - } - else { + } else { // 未绑定 console.log(` getUDP2 has no udclent and bind `); - const udpClient2: UdpClientByCenter = new UdpClientByCenter(result.udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) + 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) => { 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] == 6){ + console.info('surenjun', `接收到平台停考指令,请求指令为:${val.body[1]}`) + globalThis.judgeUdp.askStopExam(val.body[1]) + } + 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.body[0] == 18){ + //上传日志和轨迹 + uploadLogFile() + } + } + 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 = [] @@ -209,6 +221,13 @@ export async function getUDP2(context,errorFlag?) { placeId: globalThis.carInfo.examinationRoomId } globalThis.udpClient2.send(param) + }else if(val.id == '39'){ + //确定远程终止 + const lsh = val.body.map(byte => String.fromCharCode(byte)).join('') + if( lsh == globalThis.lsh ){ + globalThis.udpEvent.sendStopExam() + globalThis.judgeUdp.confirmStopExam(globalThis.signNum) + } } }) } @@ -225,28 +244,30 @@ export async function getUDP2(context,errorFlag?) { console.log(` getUDP2 has udclent ,close and rebind `); globalThis.udpClient2.closeUdp(async () => { setTimeout(() => { - globalThis.udpClient2.rebindUdp(result[0].udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) - globalThis.udpClient2.onError_Callback(()=>{ + globalThis.udpClient2.rebindUdp(result[0].udplocalIp, '8800', globalThis.carInfo?.udpAddress, + globalThis.carInfo?.messagePort) + 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) }) - } - else { + } else { // 未绑定 console.log(` getUDP2 has no udclent and bind `); - const udpClient2: UdpClientByCenter = new UdpClientByCenter(result[0].udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) + 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] @@ -285,7 +306,7 @@ export async function setTopLineUdp() { // const config = await getSyncData('IpConfigTable'); if (config && config.udplocalIp) { - const {udplocalIp,udpOppositeIp,udpOppositeIpPort} = config; + const { udplocalIp, udpOppositeIp, udpOppositeIpPort } = config; const udpClient: UdpClientByCenter = new UdpClientByCenter(udplocalIp, '55509', udpOppositeIp, udpOppositeIpPort) udpClient.bindUdp() @@ -314,17 +335,19 @@ export async function setJudgeUdp() { }, 1000); if (config && config.udplocalIp) { - const {udplocalIp} = config; + const { udplocalIp } = config; const udpClientbyCenter: UdpClientByCenter = new UdpClientByCenter( udplocalIp, '8080', 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) => { + }) //远程监听开始考试、结束考试、扣分指令 @@ -343,7 +366,7 @@ export async function setJudgeUdp() { }, //申请远程扣分查询 - askKf(directives){ + askKf(directives) { globalThis.udpClient2.sendMsgExt({ id: 35, list: [directives], @@ -354,17 +377,58 @@ 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 }) console.info('surenjun', `考车发送确定扣分指令,指令为:${directives}`) }, + + //申请语音对讲 + askVoice(){ + console.log('surenjun','发送语音对讲') + //udp bug 连发消息 + let num =0; + let timer = setInterval(()=>{ + globalThis.udpClient2.sendMsgExt({ + id: 49, + list: ['1'], + carNo: globalThis.carInfo.carNo, + placeId: globalThis.carInfo.examinationRoomId, + }) + num++; + if(num >=5){ + clearInterval(timer) + } + },200) + + }, + + //查询远程终止考试 + askStopExam(directives){ + globalThis.udpClient2.sendMsgExt({ + id: 38, + list: [directives], + carNo: globalThis.carInfo.carNo, + placeId: globalThis.carInfo.examinationRoomId + }) + }, + // 确定远程终止考试 + confirmStopExam(directives){ + console.log('surenjun','确定远程终止考试 directives=》'+directives) + globalThis.udpClient2.sendMsgExt({ + id: 40, + list: [directives,1], + carNo: globalThis.carInfo.carNo, + placeId: globalThis.carInfo.examinationRoomId + }) + } } } } + // globalThis.udpClient.bindUdp() diff --git a/entry/src/main/ets/common/utils/GpsTcpClient.ts b/entry/src/main/ets/common/utils/GpsTcpClient.ts new file mode 100644 index 00000000..d78624cd --- /dev/null +++ b/entry/src/main/ets/common/utils/GpsTcpClient.ts @@ -0,0 +1,55 @@ +import FileUtil from '../../common/utils/File'; +import { GlobalConfig } from '../../config/index'; +import socket from '@ohos.net.socket'; + +const TAG = '[GpsTcpClient]' +export default class GpsTcpClient{ + + private LocalIp: string + private errorLength: number = 0 + private tcp: socket.TCPSocket + constructor() { + this.init() + } + + async init(){ + const fileUtil = new FileUtil(globalThis.context) + const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); + const result = JSON.parse(data) + this.LocalIp = result.udplocalIp; + this.tcp = socket.constructTCPSocketInstance(); + + await this.tcp.bind({ + address: this.LocalIp, + port:31015, + family: 1 + }); + + try { + const res = await this.tcp.connect({ + address:{ + address: '192.168.7.100', + port:30015 + } + }) + } catch (e) { + this.errorLength += 1 + console.log(TAG +'connect error',JSON.stringify(e)) + } + + this.tcp.on('error', (data) => { + console.log(TAG + 'on error',JSON.stringify(data)) + if(this.errorLength < 5){ + this.init() + } + }) + } + + public async sendGpsMsg(data:ArrayBuffer){ + try { + await this.tcp.send({data}) + } catch (e) { + console.log(TAG + 'send error',JSON.stringify(e)) + } + } +} \ No newline at end of file diff --git a/entry/src/main/ets/common/utils/TcpClient.ts b/entry/src/main/ets/common/utils/TcpClient.ts index 5dce6e1c..f14066b8 100644 --- a/entry/src/main/ets/common/utils/TcpClient.ts +++ b/entry/src/main/ets/common/utils/TcpClient.ts @@ -1,10 +1,9 @@ import socket from '@ohos.net.socket'; import hilog from '@ohos.hilog'; import { getTCP } from './GlobalTcp'; -import prompt from '@ohos.prompt'; import FileUtil from './File'; import { dateFormat } from './tools'; - +import Prompt from '@system.prompt'; const TAG = 'socketTag[TcpDemo.TcpClient]' export default class TcpClient { @@ -48,8 +47,6 @@ export default class TcpClient { }); } - - bindTcp() { this.writeLog({ time:dateFormat(new Date()), @@ -169,15 +166,8 @@ export default class TcpClient { // PLC:`${TAG} Tcponmessage`, // }) globalThis.tcpUdpError = false - - // console.log('messageLengt',,value.message.length)) - // console.log("on message, message:" + value.message+ ", remoteInfo:" ) if (value) { - let dataView = new DataView(value.message) - // const Arraybuffer=buffer.from(value.message, 5, dataView?.byteLength); - const Arraybuffer = value.message.slice(5, dataView?.byteLength); - - callback && callback(Arraybuffer) + callback && callback(value.message) } else { callback && callback('') } @@ -187,15 +177,12 @@ export default class TcpClient { if (globalThis.tcpUdpError) { console.log(TAG,'tcp信号丢失') // getTCP() - prompt.showToast({ + Prompt.showToast({ message: 'tcp信号丢失', duration: 2000 }); } - this.writeLog({ - time:dateFormat(new Date()), - message: `${TAG} tcp信号丢失`, - }) + globalThis.tcpUdpError = true; },3000) // callback(value.message) diff --git a/entry/src/main/ets/common/utils/TcpRequest.ts b/entry/src/main/ets/common/utils/TcpRequest.ts index 0449b279..2c8bcb7e 100644 --- a/entry/src/main/ets/common/utils/TcpRequest.ts +++ b/entry/src/main/ets/common/utils/TcpRequest.ts @@ -164,7 +164,6 @@ class TcpUtils { if (log) { console.log(tag, 'send', message) } - this.fileUtil.addFile(this.path + 'temp.txt', `^#${message}#$`) this.socket.send({ data: `^#${message}#$` }).then(() => { diff --git a/entry/src/main/ets/common/utils/UdpClientByCenter.ts b/entry/src/main/ets/common/utils/UdpClientByCenter.ts index d1891209..d607ce8a 100644 --- a/entry/src/main/ets/common/utils/UdpClientByCenter.ts +++ b/entry/src/main/ets/common/utils/UdpClientByCenter.ts @@ -13,22 +13,20 @@ * limitations under the License. */ -// @ts-ignore import socket, { UDPSocket } from '@ohos.net.socket'; -import { Array2Byte } from '../utils/tools' -import FileUtil from '../../common/utils/File' -import { fillZero, string2Bytes } from '../utils/tools' - -const TAG = '[UdpDemo.UdpClient]' -import hilog from '@ohos.hilog'; -import prompt from '@ohos.prompt' +import { Array2Byte, dateFormat, fillZero, string2Bytes } from '../utils/tools'; +import FileUtil from '../../common/utils/File'; +import prompt from '@ohos.prompt'; import promptAction from '@ohos.promptAction'; import { getUDP } from './GlobalUdp'; -import { dateFormat } from '../utils/tools' -import { getSyncData } from '../service/initable'; +import RearEndUnitsTool from '../rearEndUnitsTool/index' +import { getCurrentTime } from '../../common/utils/tools'; + +const TAG = '[UdpDemo.UdpClient]' export default class UdpClientByCenter { + public currentValue: string = '' private localIp: string = '' private localIpPort: string = '' private oppositeIp: string = '' @@ -43,15 +41,14 @@ export default class UdpClientByCenter { private context private folderPath private stashFn: StashFunction - private errorStep: number=0 + private errorStep: number = 0 private interval private headLenth: number = 9 //消息头长度 private isWorking: Boolean = false private plcUdpError = false; private initParam - private onMessage_1Callback:Function = ()=>{} - public currentValue:string = '' + private retClass: RearEndUnitsTool constructor(udplocalIp: string, udplocalIpPort: string, udpOppositeIp: string, udpOppositeIpPort: string) { this.localIp = udplocalIp @@ -62,14 +59,18 @@ export default class UdpClientByCenter { } this.udp = socket.constructUDPSocketInstance(); this.initPath() + if (!globalThis.retClass) { + globalThis.retClass = new RearEndUnitsTool(globalThis.context) + } + this.retClass = globalThis.retClass + console.log(`${TAG} init UdpClientByCenter`) } getStatus() { return this.isWorking } - rebindUdp(localIp: string, localIpPort: string, oppositeIp: string, oppositeIpPort: string) - { + rebindUdp(localIp: string, localIpPort: string, oppositeIp: string, oppositeIpPort: string) { this.localIp = localIp this.oppositeIp = oppositeIp this.localIpPort = localIpPort @@ -87,13 +88,18 @@ export default class UdpClientByCenter { // time:dateFormat(new Date()), // PLC:`${TAG} getUDPudp rebind success`, // }) + const terType = this.retClass.terType + //TODO 临时处理过滤掉中心udp + if(localIpPort != '8800' && terType == 2){ + this.udp && this.udp.on('message', this.message_1Fn); + } }).catch(err => { //globalThis.closeHeartSocket=true this.isWorking = false - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} getUDPudp rebind failed:${JSON.stringify(err)}`, - // }) + // this.writeLog({ + // time:dateFormat(new Date()), + // PLC:`${TAG} getUDPudp rebind failed:${JSON.stringify(err)}`, + // }) console.log(`${TAG} getUDPudp rebind failed:${JSON.stringify(err)}`); }); } @@ -103,13 +109,20 @@ export default class UdpClientByCenter { address: this.localIp, port: parseInt(this.localIpPort), family: 1 }); promise.then(() => { + const localIpPort = this.localIpPort this.isWorking = true // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG} getUDPudp bind success`, // }) + const terType = this.retClass.terType + //TODO 临时处理过滤掉中心udp + if(localIpPort != '8800' && terType == 2){ + this.udp && this.udp.on('message', this.message_1Fn); + } }).catch(err => { this.isWorking = false + console.info('surenjun err=>', JSON.stringify(err)) // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG} getUDPudp bind error${JSON.stringify(err)},localIp:${this.localIpPort},port:${this.localIpPort}`, @@ -135,9 +148,6 @@ export default class UdpClientByCenter { return view; } - //length消息体bufferlength id消息类型id bodyStr消息体string - // setMsyBody(id,bodyByte){ - // {id: 31,list:[0,1,'0000000000000'],carNo:489,placeId:62} setWholeMsg(params) { let head = this.setMsgHead(params); @@ -150,14 +160,17 @@ export default class UdpClientByCenter { } - setMsgHead({id, list, placeId=62, carNo=489}) { + //length消息体bufferlength id消息类型id bodyStr消息体string + // setMsyBody(id,bodyByte){ + + setMsgHead({ id, list, placeId=62, carNo=489 }) { let a = string2Bytes(`${id}${fillZero(placeId, 3)}`, 2 * 8); let b = string2Bytes(`${fillZero(carNo, 4)}${globalThis.lshNo}`, 4 * 8); let c = string2Bytes(list.length, 2 * 8); return [...a, ...b, ...c]; } - setMsgBody({id,list}) { + setMsgBody({ id, list }) { let tmpList = [] tmpList = list @@ -171,15 +184,14 @@ export default class UdpClientByCenter { console.log('getUDPsendHeadMsg exit') } - sendMsg(msg, sendCallback?) - { - if (!this.isWorking ) { + sendMsg(msg, sendCallback?) { + if (!this.isWorking) { // console.log(`${TAG}getUDPudpCLient sendMsg is closed return `); // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG}getUDPudpCLient sendMsg is closed return oppositeIp:${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort:${this.localIpPort}`, // }) - if(sendCallback) { + if (sendCallback) { sendCallback() } return; @@ -205,8 +217,8 @@ export default class UdpClientByCenter { // PLC:`${TAG}getUDPudpCLient udp send fail:oppositeIp${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort,${this.localIpPort}${JSON.stringify(err)}`, // }) promptAction.showToast({ - message:`${TAG}getUDPudpCLient udp send fail:oppositeIp${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort,${this.localIpPort}`, - duration:4000 + message: `${TAG}getUDPudpCLient udp send fail:oppositeIp${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort,${this.localIpPort}`, + duration: 4000 }) }); } @@ -243,6 +255,7 @@ export default class UdpClientByCenter { this.stashFn = callback ? callback : () => { } } + //中心udp回执 onMessage_2(callback, type?) { this.udp.on('message', (value, remoteInfo) => { @@ -251,6 +264,9 @@ export default class UdpClientByCenter { for (let i = 0; i < dataView?.byteLength; ++i) { arr[i] = dataView?.getUint8(i) } + if (!arr.length) { + return + } let idNum = '0x' + fillZero(arr[1].toString(16), 2) + fillZero(arr[0].toString(16), 2); let id = Math.floor(+idNum / 1000) @@ -261,14 +277,19 @@ export default class UdpClientByCenter { list.push(arr[i]) } this.stashFn({ - id, length, body: list, sendId: this.sendId + id, + length, + body: list, + sendId: this.sendId }) callback({ - id, length, body: list, sendId: this.sendId + id, + length, + body: list, + sendId: this.sendId }) - // this.interval=setInterval(()=>{ // // },3000) @@ -299,17 +320,28 @@ export default class UdpClientByCenter { //plc onMessage_1(callback?) { - this.onMessage_1Callback = callback; - this.udp&&this.udp.on('message', this.message_1Fn); + const terType = globalThis.retClass?.terType; + if (terType == 2) { + //三型机 + this.onMessage_1Callback = callback; + } else { + this.retClass.receiveMsg(callback) + //TODO 临时处理 + globalThis.retClass = this.retClass + } + + // this.udp && this.udp.on('message', this.message_1Fn); } - closeMessage_1(){ + + closeMessage_1() { console.info('surenjun', 'getUDP关闭udp message监听事件') - this.udp.off('message',this.message_1Fn); + this.udp.off('message', this.message_1Fn); console.info('surenjun', 'getUDP关闭udp message监听事件 成功') } - message_1Fn = (value)=>{ + message_1Fn = async (value) => { + // console.info('surenjun2','set message_1Fn=>' + await getCurrentTime()) let callback = this.onMessage_1Callback // 收到的是ArrayBuffer 需要进行转换解析 this.plcUdpError = false @@ -336,17 +368,19 @@ export default class UdpClientByCenter { // time:dateFormat(new Date()), // PLC: JSON.stringify(newArr.toString()), // }) - if(strachArr[83]!='4'){ - console.log('差分状态异常',strachArr[83],strachArr[92]) + if (strachArr[83] != '4') { + console.log('差分状态异常', strachArr[83], strachArr[92]) this.writeLog({ - time:dateFormat(new Date()), + time: dateFormat(new Date()), PLC: `${TAG}差分状态异常,${strachArr[83]},${strachArr[92]}`, }) - }else{ - globalThis.dialogOpen=false - this.chafenFlag=0 + } else { + globalThis.dialogOpen = false + this.chafenFlag = 0 } + // console.info('surenjun2','set message_1Fn=>' + newArr.toString()) callback && callback(newArr.toString()) + console.info('surenjun 左方向灯=>', newArr.toString()) this.currentValue = newArr.toString(); } else { callback && callback('') @@ -354,15 +388,18 @@ export default class UdpClientByCenter { this.testIfUdpConnetced(callback) } - async writeLog(param){ + + async writeLog(param) { // const fileUtil = new FileUtil(globalThis.context) // fileUtil.editFile(`${this.folderPath}/plcLog.txt`, JSON.stringify(param)+`\n`) } - async initPath(){ + + async initPath() { // const fileUtil = new FileUtil(globalThis.context) // const date=dateFormat(new Date).split(' ')[0] // this.folderPath = await fileUtil.initFolder(`/PLC/${date}`); } + //获取当前UDP信号 getCurrentMessage = () => { return this.currentValue @@ -376,7 +413,7 @@ export default class UdpClientByCenter { const arrRedBuffer = Array2Byte(arrRed).buffer const arrGreenBugger = Array2Byte(arrGreen).buffer let num = 0 - globalThis.dialogOpen=false + globalThis.dialogOpen = false //监听udp是否断开 clearInterval(globalThis.messageTimer) @@ -389,15 +426,15 @@ export default class UdpClientByCenter { if (this.plcUdpError) { num++ this.writeLog({ - time:dateFormat(new Date()), + time: dateFormat(new Date()), PLC: 'plc udp信号丢失', }) console.log(TAG, 'plc udp信号丢失') if (num == 3) { - getUDP(globalThis.context,true) - globalThis.title='plc udp信号丢失' - globalThis.type='3' - if(!globalThis.dialogOpen){ + getUDP(globalThis.context, true) + globalThis.title = 'plc udp信号丢失' + globalThis.type = '3' + if (!globalThis.dialogOpen) { // AppStorage.SetOrCreate('errorCode', 1); // if(this.errorStep!=1){ // console.log('sys.v_valuesys.v_valuesys.v_value11221') @@ -437,6 +474,9 @@ export default class UdpClientByCenter { }, 2000) } + private onMessage_1Callback: Function = () => { + } + // initHeartSendMsg(param,context){ // console.log('1111param',JSON.stringify(param)) // this.initParam=param diff --git a/entry/src/main/ets/common/utils/UdpEvent.ets b/entry/src/main/ets/common/utils/UdpEvent.ets index 0ebf70db..d260ae4c 100644 --- a/entry/src/main/ets/common/utils/UdpEvent.ets +++ b/entry/src/main/ets/common/utils/UdpEvent.ets @@ -11,7 +11,9 @@ export const EVENTID = { //远程开始考试 beginExamEventId: 11, //远程结束考试 - endExamEventId: 12 + endExamEventId: 12, + //远程终止考试 + stopExamEventId: 40 } export default class JudgeEmitter { @@ -19,6 +21,7 @@ export default class JudgeEmitter { private endExamCallBack: Function = () => {} private confirmExamCallBack: Function = () => {} private kfContent: Function = () => {} + private stopExam: Function = () => {} private directives: string @@ -32,6 +35,7 @@ export default class JudgeEmitter { emitter.off(EVENTID.endExamEventId) emitter.off(EVENTID.kfConfirmEventId) emitter.off(EVENTID.kfEventId) + emitter.off(EVENTID.stopExamEventId) emitter.on({ eventId: EVENTID.beginExamEventId @@ -52,6 +56,12 @@ export default class JudgeEmitter { this?.kfContent(data) }); + emitter.on({ + eventId: EVENTID.stopExamEventId + }, (data) => { + this?.stopExam(data) + }); + } //监听开始考试 @@ -72,6 +82,11 @@ export default class JudgeEmitter { this.kfContent = callBack } + public onStopExam = async (callBack?: Function) => { + console.info('surenjun', '注册远程扣分考试事件') + this.stopExam = callBack + } + //开始考试 public sendBeginExam = async (content: string) => { emitter.emit({ @@ -94,6 +109,15 @@ export default class JudgeEmitter { }); } + //结束考试 + public sendStopExam = async () => { + emitter.emit({ + eventId: EVENTID.stopExamEventId + }, { + data: {} + }); + } + //扣分 public sendKfContent = async (kfxh: string) => { const directives = this.directives diff --git a/entry/src/main/ets/common/utils/UdpJudge.ts b/entry/src/main/ets/common/utils/UdpJudge.ts index 1a287d58..f5e3b4ce 100644 --- a/entry/src/main/ets/common/utils/UdpJudge.ts +++ b/entry/src/main/ets/common/utils/UdpJudge.ts @@ -57,13 +57,14 @@ export const getMessageHeartbeat = async (msg) => { const carInfo = globalThis.carInfo; const { examSubject,plateNo } = carInfo; const ksyh='0000000000000' + '0000000000000' const {fourInOneScreen:{gpsDigit}} = judgeConfig const asclshArr = stringToASC(fillZero( globalThis.singlePlay - ? '1111111111111' - : globalThis.lsh, + ? (examSubject == 2 ? '0000000000000' : '0000000000000') + : (globalThis.lsh || '0000000000000'), 13)); - const ascksyhArr = stringToASC(fillZero(examSubject == 2 ? '0000000000000':'1111111111111', 13)) + const ascksyhArr = stringToASC(fillZero(ksyh, 13)) const ascsbxhArr = stringToASC('00000000') // const ascsbxhArr = stringToASC('153216400880') const serialIndex = globalThis.serialIndex @@ -87,9 +88,8 @@ export const getMessageHeartbeat = async (msg) => { if(tempSd < 1){ tempSd = 0 } - const arr = [ - //考生号 + //考生号 asclshArr.map(lsh => string2Bytes(lsh, 8)[0]), //考试员号 ascksyhArr.map(ksyh => string2Bytes(ksyh, 8)[0]), @@ -140,7 +140,6 @@ export const getMessageHeartbeat = async (msg) => { arr.forEach(itemArr => { tempArr = tempArr.concat(itemArr) }) - globalThis.serialIndex = 0; return Array2Byte(tempArr) } @@ -262,8 +261,8 @@ const getPlcData = async (plc: string) => { //TODO gps数据 //gps时间 经度 纬度 航向角 俯仰角 海拔高 高度差 速度 sj: time, - jd: p[96], - wd: p[95], + jd: Math.max(Number(p[95]),Number(p[96])), + wd: Math.min(Number(p[95]),Number(p[96])), hxj: p[90], fyj: p[91], hbg: p[85], @@ -284,13 +283,22 @@ const getPlcData = async (plc: string) => { const getDwStatusType = (dw)=> { switch (dw){ - case 0:return [0,0,0,0] + case 0: return [0,0,0,0] case 1: return [0,0,0,1] case 2: return [0,0,1,0] case 3: return [0,0,1,1] case 4: return [0,1,0,0] case 5: return [0,1,0,1] + //R档 case 9: return [1,0,0,1] - default :return [0,0,0,0] + //P档位 + case 10: return [1,0,1,0] + //D档 + case 11: return [1,0,1,1] + //S档 + case 12: return [1,1,0,0] + //M档 + case 13: return [1,1,0,1] + default :return [0,0,0,0] } } \ No newline at end of file diff --git a/entry/src/main/ets/common/utils/UdpUtils.ets b/entry/src/main/ets/common/utils/UdpUtils.ets new file mode 100644 index 00000000..e69de29b diff --git a/entry/src/main/ets/common/utils/aioTool.ts b/entry/src/main/ets/common/utils/aioTool.ts new file mode 100644 index 00000000..0f777c10 --- /dev/null +++ b/entry/src/main/ets/common/utils/aioTool.ts @@ -0,0 +1,110 @@ +import HiSerialSDK from '@ohos.hiserialsdk'; + +// 打开串口工具 +export const OpenSerialPort = (serialPort: string) => { + return new Promise((resolve, reject) => { + HiSerialSDK.SerialOpenAsync(serialPort, (value: number) => { + if (value === -1) { + console.log("打开串口失败!") + reject(-1) + } + console.log("打开成功!!") + resolve(value) + }) + }) +} + +//初始化串口数据 +export const InitSerialPortData = + async (fd: number, speed: number) => { + return new Promise((resolve, reject) => { + console.log("打印各个参数") + console.log("fd:" + fd) + console.log("speed:" + speed) + HiSerialSDK.SerialSetAsync(fd, speed, 0, 8, 1, 0x4e, (value: number) => { + // 0 成功 -1失败 + if (value === 0) { + console.log("初始化成功!") + resolve(true) + } + if (value === -1) { + console.log("初始化失败!") + reject(false) + } + }) + }) + } + +//发送数据 +export const SendSerialPortData = (fd: number, data: number[]) => { + return new Promise((resolve, reject) => { + HiSerialSDK.SerialSendAsync(fd, data, (value: number) => { + if (value === -1) { + console.log("surenjun" + "发送失败!") + reject(-1) + } + resolve(value) + }) + }) +} + +// 接受数据 +export const ReceiveSerialPortData = (fd: number, timeout: number,) => { + return new Promise((resolve) => { + HiSerialSDK.SerialRecvAsync(fd, timeout, (value: HiSerialSDK.receiveInfo) => { + resolve(value) + }) + }) +} + +// 主动接受数据 +export const ReceiveSerialPortDataBySelf = (fd: number, callback: Function) => { + HiSerialSDK.SerialListenCallbackSet(fd, callback) +} + +// 取消主动接受 +export const CancelReceiveSerialPortData = async (fd: number) => { + return new Promise((resolve, reject) => { + let result = HiSerialSDK.SerialListenCallbackCancel(fd) + if (result === 0) { + resolve(true) + } else { + reject(false) + } + }) +} + +//关闭串口 +export const CloseSerialPort = (fd: number) => { + return new Promise((resolve, reject) => { + HiSerialSDK.SerialCloseAsync(fd, (value: number) => { + if (value === 0) { + console.log("关闭串口成功!") + resolve(true) + } + if (value === -1) { + console.log("关闭串口失败!") + reject(false) + } + }) + }) +} + +/** + * 将输入字符串转换为ASCII码数组 + * @param input 要转换的输入字符串 + * @returns 转换后的ASCII码数组 + */ +export const ConvertToASCII = (input: string): number[] => { + return input.split('').map(char => char.charCodeAt(0)); +} + +/** + * 将输入字符串转换为十六进制(hex)数组 + * @param input 要转换的输入字符串 + * @returns 转换后的十六进制数组 + */ +export const ConvertToHex = (input: string): number[] => { + return input.split('').map(char => parseInt(char.charCodeAt(0).toString(16), 16)); +} + diff --git a/entry/src/main/ets/common/utils/new/udp.ets b/entry/src/main/ets/common/utils/new/udp.ets new file mode 100644 index 00000000..8c4200ca --- /dev/null +++ b/entry/src/main/ets/common/utils/new/udp.ets @@ -0,0 +1,126 @@ +import socket from '@ohos.net.socket'; + +/** + * UDP工具类 + * 功能:创建UDP Socket、发送消息、接收消息、广播控制、关闭连接 + */ +export class UdpTool { + private udpSocket: socket.UDPSocket | null = null; + private receiveCallback: ((data: string, remoteInfo: RemoteInfo) => void) | null = null; + private errorCallback: ((error: Error) => void) | null = null; + + /** + * 初始化UDP Socket + * @param port 绑定端口号 + * @param callback 接收消息回调 + */ + async initialize(port: number, callback?: (data: string, remoteInfo: RemoteInfo) => void): Promise { + try { + // 1. 创建UDP Socket实例 + this.udpSocket = socket.constructUDPSocketInstance(); + + // 2. 绑定本地端口 + await this.udpSocket.bind({ address: '0.0.0.0', port: port, family: 1 }); + + // 3. 注册消息监听 + this.udpSocket.on('message', (payload: { + message: ArrayBuffer, + remoteInfo + }) => { + const msg = this.arrayBufferToString(payload.message); + this.receiveCallback?.(msg, payload.remoteInfo); + }); + // 4. 注册错误监听 + this.udpSocket.on('error', (err) => { + this.errorCallback?.(new Error(`Socket error: ${err.code} - ${err.message}`)); + }); + + if (callback) { + this.receiveCallback = callback; + } + } catch (error) { + throw new Error(`UDP初始化失败: ${error.message}`); + } + } + + /** + * 发送UDP消息 + * @param message 发送内容 + * @param address 目标地址 + * @param port 目标端口 + */ + async send(message: string, address: string, port: number): Promise { + if (!this.udpSocket) { + throw new Error('Socket未初始化'); + } + + try { + const data = this.stringToArrayBuffer(message); + await this.udpSocket.send({ + data: data, + address: { address: address, port: port, family: 1 } + }); + } catch (error) { + throw new Error(`消息发送失败: ${error.message}`); + } + } + + /** + * 设置广播模式 + * @param enable 是否启用广播 + */ + setBroadcast(enable: boolean): void { + if (!this.udpSocket) { + throw new Error('Socket未初始化'); + } + + try { + this.udpSocket.setExtraOptions({ broadcast: enable }); + } catch (error) { + throw new Error(`广播设置失败: ${error.message}`); + } + } + + /** + * 关闭Socket连接 + */ + close(): void { + if (this.udpSocket) { + this.udpSocket.off('message'); + this.udpSocket.off('error'); + this.udpSocket.close(); + this.udpSocket = null; + } + } + + /** + * 设置错误回调 + */ + onError(callback: (error: Error) => void): void { + this.errorCallback = callback; + } + + // 工具方法:ArrayBuffer转String + private arrayBufferToString(buffer: ArrayBuffer): string { + return String.fromCharCode(...new Uint8Array(buffer)); + } + + // 工具方法:String转ArrayBuffer + private stringToArrayBuffer(str: string): ArrayBuffer { + const buffer = new ArrayBuffer(str.length); + const view = new Uint8Array(buffer); + for (let i = 0; i < str.length; i++) { + view[i] = str.charCodeAt(i); + } + return buffer; + } +} + +/** + * 远程设备信息类型 + */ +interface RemoteInfo { + address: string; + port: number; + family: number; +} \ No newline at end of file diff --git a/entry/src/main/ets/common/utils/tempRequest.ts b/entry/src/main/ets/common/utils/tempRequest.ts index 6b1a3cd1..bad7cb50 100644 --- a/entry/src/main/ets/common/utils/tempRequest.ts +++ b/entry/src/main/ets/common/utils/tempRequest.ts @@ -52,6 +52,11 @@ export default async function tempRequest(req: any): Promise { if (typeof res === "string") { res = JSON.parse(res) } + + if(res.code !== undefined){ + resolve(res) + return + } //处理中心服务code if (res.Envelope) { const msgXml = res.Envelope.Body.writeObjectOutResponse.return; @@ -94,13 +99,14 @@ export default async function tempRequest(req: any): Promise { reject(res) } }).catch(Error => { - console.info('test-error0' + url + ' error:resp: ' + JSON.stringify(Error.message)) - Prompt.showToast({ - message: Error?.message, - duration: 5000 - }); - reject(Error) - }) + console.info('test-error0' + url + ' error:resp: ' + JSON.stringify(Error.message)) + httpRequest.destroy(); + Prompt.showToast({ + message: Error?.message, + duration: 5000 + }); + reject(Error) + }) } catch (e) { console.info('test-error' + url + ' error:resp: ' + JSON.stringify(e)) diff --git a/entry/src/main/ets/config/global.ts b/entry/src/main/ets/config/global.ts index 6e16dd4d..cbb85f4f 100644 --- a/entry/src/main/ets/config/global.ts +++ b/entry/src/main/ets/config/global.ts @@ -16,7 +16,7 @@ export const GlobalConfig={ //杭州 hz:{ km2:['2022.03.14.01','2022.03.17.1'], - km3:[], + km3:['2024.08.21.01','2024.08.24.1'], }, //黑龙江 hlg:{ @@ -37,5 +37,21 @@ export const GlobalConfig={ km2:['2024.08.21.01','2024.08.24.1'], km3:[], }, + wx:{ + km2:['2024.08.21.01','2024.08.24.1'], + } + }, + + serialPortConfig:{ + gps:{ + portName:'COM7', + path:'/dev/ttyS7', + baudRate:115200 + }, + obd:{ + portName:'COM5', + path:'/dev/ttyS5', + baudRate:115200 + } } } diff --git a/entry/src/main/ets/entryability/EntryAbility.ts b/entry/src/main/ets/entryability/EntryAbility.ts index 5e598609..9e7393e9 100644 --- a/entry/src/main/ets/entryability/EntryAbility.ts +++ b/entry/src/main/ets/entryability/EntryAbility.ts @@ -47,8 +47,8 @@ export default class EntryAbility extends UIAbility { // globalThis.judgeVersion ='2024.08.24.1' // globalThis.version ='2023.12.13.01'; - globalThis.version = GlobalConfig.version.jn.km3[0]; - globalThis.judgeVersion = GlobalConfig.version.jn.km3[1]; + globalThis.version = GlobalConfig.version.wx.km2[0]; + globalThis.judgeVersion = GlobalConfig.version.wx.km2[1]; globalThis.tcpSendNum = 0 globalThis.videoVersion = '1.0' diff --git a/entry/src/main/ets/mock/CarCheck.ets b/entry/src/main/ets/mock/CarCheck.ets index 2e47c27f..4b1d8449 100644 --- a/entry/src/main/ets/mock/CarCheck.ets +++ b/entry/src/main/ets/mock/CarCheck.ets @@ -107,8 +107,8 @@ export const WarnFlagTipData = { 9: ['dianhuoVideo.wav', 'xihuoVideo.wav'], 10: ['check31.wav'], 11: ['check30.wav'], - 12: ['check28.wav'], - 13: ['check29.wav'], + 12: ['check29.wav'], + 13: ['check28.wav'], 14: ['check11.wav'], 15: ['check12.wav'], 16: ['check13.wav'], @@ -136,8 +136,8 @@ export const RealNumData = { 8: 18, 9: 5, 10: 29, - 11: 30, - 12: 31, + 11: 31, + 12: 30, 13: 32, 14: 28, 15: 28, diff --git a/entry/src/main/ets/mock/PLCGPSData.ts b/entry/src/main/ets/mock/PLCGPSData.ts new file mode 100644 index 00000000..d84d4b7c --- /dev/null +++ b/entry/src/main/ets/mock/PLCGPSData.ts @@ -0,0 +1,101 @@ +export const PLCGPSData = [ + "#DN_GD", + "$PLC", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0_0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0_0_0_0", + "0.0.0.0", + "V9.1_V2.1_1", + "65535", + "1", + "V7.8", + "0/0", + "0/0", + "0", + "0/0", + "100*200-2-2-。。", + "1", + "2", + "3", + "4", + "5", + "6", + "7", + "8", + "9", + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "#END$GPS", + "1", + "16", + "6.068", + "1.301", + "0", + "1.07", + "0.64", + "0", + "0", + "0-12", + "91022", + "80109.2", + "3155.6715075", + "11851.9196718", + "0.012", + "#END", +]; \ No newline at end of file diff --git a/entry/src/main/ets/mock/index.ets b/entry/src/main/ets/mock/index.ets deleted file mode 100644 index add1ef21..00000000 --- a/entry/src/main/ets/mock/index.ets +++ /dev/null @@ -1,9 +0,0 @@ -export * from "./CandidateData" - -export * from "./VideoData" - -export * from "./Judge" - -export * from "./SignDisplay" - -export * from "./CarCheck" \ No newline at end of file diff --git a/entry/src/main/ets/mock/index.ts b/entry/src/main/ets/mock/index.ts index add1ef21..30eb68c8 100644 --- a/entry/src/main/ets/mock/index.ts +++ b/entry/src/main/ets/mock/index.ts @@ -6,4 +6,6 @@ export * from "./Judge" export * from "./SignDisplay" -export * from "./CarCheck" \ No newline at end of file +export * from "./CarCheck" + +export * from "./PLCGPSData" \ No newline at end of file diff --git a/entry/src/main/ets/pages/CarCheck.ets b/entry/src/main/ets/pages/CarCheck.ets index 6205345a..d139ddec 100644 --- a/entry/src/main/ets/pages/CarCheck.ets +++ b/entry/src/main/ets/pages/CarCheck.ets @@ -5,6 +5,9 @@ import TopLogo from './compontents/TopLogo'; import testNapi from '@ohos.hiserialsdk'; import { dateFormat } from '../common/utils/tools'; import { DwMapData, PassData, RealNumData, StackValueData, WarnFlagData, WarnFlagTipData } from '../mock'; +import FileUtil from '../common/utils/File'; +import { GlobalConfig } from '../config'; +import common from '@ohos.app.ability.common'; @Entry @Component @@ -37,6 +40,7 @@ export default struct Index { @State stopFlag: boolean = false @State fromIndex: boolean = false private vocObj = null; + private context = getContext(this) as common.UIAbilityContext; // private AccountTable = new AccountTable(()=>{},CommonConstants); aboutToAppear() { @@ -114,28 +118,66 @@ export default struct Index { } // - carConfigurationInfoFn() { - // const fileUtil = new FileUtil(context) - // const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/deviceNo.txt'); - // if (data === '' || data === undefined) { - // promptAction.showToast({ - // message: `请先进行设备注册`, - // duration: 3000 - // }); - // globalThis.type='1' - // globalThis.title=decodeURIComponent('请先进行设备注册') - // globalThis.errorDialog.open() - // resolve('') - // } else { - // const fileData=JSON.parse(data) - // globalThis.deviceNo = fileData.deviceName - // console.log('globalThis.deviceNo', globalThis.deviceNo) - // // getCarInfo() - // resolve(fileData.deviceName) - // } - if (globalThis.singlePlay) { - const str = "1:5;2:5;3:5;4:5;5:5;6:5;7:5;8:5;9:5;10:5;11:5;12:5;13:5;14:5;15:5;16:5;17:5;18:5;19:5;20:5;21:5;22:2;23:5;24:5" - const data = str.split(';') + async carConfigurationInfoFn() { + const fileUtil = new FileUtil(this.context) + const checkListStr = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/carcheck.txt'); + + if (checkListStr === '' || checkListStr === undefined) { + //模拟真实数据 + const param = { + "body": + { + "carIdString": globalThis.carInfo.carId, //考车ID + "deviceNo": globalThis.deviceNo + } + } + + carConfigurationInfo(param).then(res => { + // @ts-ignore + console.log('ES_CHECK_CAR_ITEM',JSON.stringify(res.body)) + // @ts-ignore + if(res?.body?.ES_CHECK_CAR_ITEM){ + // @ts-ignore + const data = res.body.ES_CHECK_CAR_ITEM[0].ITEMS.split(';'); + this.checkList = [] + const list = data + list.map(res => { + const arr = res.split(':') + this.checkList.push({ + 'key': parseInt(arr[0]) + 2, 'time': arr[1] + }) + }) + this.checkListCopy = JSON.parse(JSON.stringify(this.checkList)) + }else{ + const str = "1:5;2:5;3:5;4:5;5:5;6:5;7:5;8:5;9:5;10:5;11:5;12:5;13:5;14:5;15:5;16:5;17:5;18:5;19:5;20:5;21:5;22:2;23:5;24:5" + const data = str.split(';') + this.checkList = [] + const list = data + list.map(res => { + const arr = res.split(':') + this.checkList.push({ + 'key': parseInt(arr[0]) + 2, 'time': arr[1] + }) + }) + this.checkListCopy = JSON.parse(JSON.stringify(this.checkList)) + } + + }).catch((error) => { + console.log('error12error' + error) + const str = "1:5;2:5;3:5;4:5;5:5;6:5;7:5;8:5;9:5;10:5;11:5;12:5;13:5;14:5;15:5;16:5;17:5;18:5;19:5;20:5;21:5;22:2;23:5;24:5" + const data = str.split(';') + this.checkList = [] + const list = data + list.map(res => { + const arr = res.split(':') + this.checkList.push({ + 'key': parseInt(arr[0]) + 2, 'time': arr[1] + }) + }) + this.checkListCopy = JSON.parse(JSON.stringify(this.checkList)) + }) + }else { + const data = checkListStr.split(';') this.checkList = [] const list = data list.map(res => { @@ -147,30 +189,7 @@ export default struct Index { this.checkListCopy = JSON.parse(JSON.stringify(this.checkList)) return } - //模拟真实数据 - const param = { - "body": - { - "carIdString": globalThis.carInfo.carId, //考车ID - "deviceNo": globalThis.deviceNo - } - } - carConfigurationInfo(param).then(res => { - // @ts-ignore - const data = res.body.ES_CHECK_CAR_ITEM[0].ITEMS.split(';'); - this.checkList = [] - const list = data - list.map(res => { - const arr = res.split(':') - this.checkList.push({ - 'key': parseInt(arr[0]) + 2, 'time': arr[1] - }) - }) - this.checkListCopy = JSON.parse(JSON.stringify(this.checkList)) - }).catch((error) => { - console.log('error12error' + error) - }) } async kszj() { @@ -224,8 +243,10 @@ export default struct Index { this.warnFlag[26] = '2' } } - + console.log('msgmsgmsg',msg) if (that.index == 10 || that.index == 11 || that.index == 12 || that.index == 13) { + console.log('msgmsgmsg000',that.index,that.signArr[that.realNum[that.index]]) + if (that.signArr[that.realNum[that.index]] != '1200') { that.warnFlag[that.index] = '2' } else { @@ -308,37 +329,37 @@ export default struct Index { } initfackCheck(index){ const that=this - setTimeout(()=>{ - console.log('indexindex',index) - if(index>=3){ - this.getCheckList() - return - } + setTimeout(()=>{ + console.log('indexindex',index) + if(index>=3){ + this.getCheckList() + return + } - console.log('this.index',index,) - that.passArray[index]=true - if(index==2){ - let flag=false - console.log('globalThis.spzd[key]',globalThis.spzd) + console.log('this.index',index,) + that.passArray[index]=true + if(index==2){ + let flag=false + console.log('globalThis.spzd[key]',globalThis.spzd) - for(let key in globalThis.spzd){ - console.log('globalThis.spzd[key]',globalThis.spzd[key]) - if(globalThis.spzd[key]){ - that.warnFlag[index]='1' - flag=true - } + for(let key in globalThis.spzd){ + console.log('globalThis.spzd[key]',globalThis.spzd[key]) + if(globalThis.spzd[key]){ + that.warnFlag[index]='1' + flag=true } - if(!flag){ - that.warnFlag[index]='2' - } - }else{ + } + if(!flag){ that.warnFlag[index]='2' } - that.passArray=JSON.parse(JSON.stringify(that.passArray)) - that.warnFlag=JSON.parse(JSON.stringify(that.warnFlag)) - index++ - this.initfackCheck(index) - },1000) + }else{ + that.warnFlag[index]='2' + } + that.passArray=JSON.parse(JSON.stringify(that.passArray)) + that.warnFlag=JSON.parse(JSON.stringify(that.warnFlag)) + index++ + this.initfackCheck(index) + },1000) } async getCheckList() { @@ -456,14 +477,14 @@ export default struct Index { } Row() { - Image(this.warnFlag[12] == '1' ? $r('app.media.zh_r') : this.warnFlag[12] == '2' ? $r('app.media.zh') : '') - .width(103 * this.ratio) - .height(118.5 * this.ratio) - .visibility(this.passArray[12] ? Visibility.Visible : Visibility.Hidden) - Image(this.warnFlag[13] == '1' ? $r('app.media.yh_r') : this.warnFlag[13] == '2' ? $r('app.media.yh') : '') + Image(this.warnFlag[13] == '1' ? $r('app.media.zh_r') : this.warnFlag[13] == '2' ? $r('app.media.zh') : '') .width(103 * this.ratio) .height(118.5 * this.ratio) .visibility(this.passArray[13] ? Visibility.Visible : Visibility.Hidden) + Image(this.warnFlag[12] == '1' ? $r('app.media.yh_r') : this.warnFlag[12] == '2' ? $r('app.media.yh') : '') + .width(103 * this.ratio) + .height(118.5 * this.ratio) + .visibility(this.passArray[12] ? Visibility.Visible : Visibility.Hidden) } } .backgroundImage($r('app.media.rc')) diff --git a/entry/src/main/ets/pages/Index.ets b/entry/src/main/ets/pages/Index.ets index edc3d43d..a2e0505e 100644 --- a/entry/src/main/ets/pages/Index.ets +++ b/entry/src/main/ets/pages/Index.ets @@ -10,7 +10,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 { getSingleCenterTable, setliushuiNum, takePhotoFn } from '../common/service/indexService'; +import { getSingleCenterTable, setliushuiNum, takePhotoFn ,uploadLogFile} from '../common/service/indexService'; import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl'; import promptAction from '@ohos.promptAction'; import errorMsgDialog from './compontents/errorMsgDialog'; @@ -19,6 +19,9 @@ import UdpEvent from '../common/utils/UdpEvent'; import { delPic } from '../common/service/videoService'; import imageBtn from './compontents/imageBtn'; import VoiceAnnounce from './judgeSDK/utils/voiceAnnouncements'; +import {updateModelAndCar} from '../common/autoUpdate/index' +// import {uploadLogFile} from '../common/service/indexService' +import { getModalValueCdAndCar } from '../api'; // import VoiceAnnounce from './judgeSDK/utils/voiceAnnouncements'; @@ -36,10 +39,13 @@ struct Index { @State dialogRatio: number = 0.8 @State ratio: number = 1700 / 960 @State delLoading: boolean = false + @State loadingText: string = '' @State loading: boolean = false @State initParamFlag: boolean = false @State fd: number = -1; @State num: number = 0; + //模型是否下载 + @State isModelInit: boolean = false; fileHelper = null; errorDialog: CustomDialogController = new CustomDialogController({ builder: errorMsgDialog({ @@ -148,7 +154,6 @@ struct Index { } this.testXMLToJSONInWorker() - }) } if (this.isSingle) { @@ -337,7 +342,7 @@ struct Index { .width(80 * globalThis.ratio) .height(80 * globalThis.ratio) .position({ x: 288 * globalThis.ratio, y: 89 * globalThis.ratio }) - Text('获取考车信息,请稍候……') + Text(this.loadingText ||'获取考车信息,请稍候……') .fontSize(24 * globalThis.ratio) .margin({ top: 20 * globalThis.ratio }) .fontWeight(400) @@ -433,8 +438,24 @@ struct Index { this.loading = true console.log("sql 1111") - getSingleCenterTable(param).then((ret) => { - console.log('teststetfinsh1', ret) + getSingleCenterTable(param).then(async (ret:any) => { + + if(!this.isModelInit){ + this.loading = true + this.loadingText = '正在下载考车模型,请稍候……' + await updateModelAndCar(false) + this.loading = false + this.loadingText = '' + this.isModelInit = true + } + + if(typeof ret == 'object' && ret.resultCode == '3'){ + this.loadingText = '正在下载考车最新版本,请稍候……' + this.loading = true + await updateModelAndCar(true) + this.loadingText = '正在安装考车最新版本,请稍候……' + return false + } // DB.queryListBySql('select * from MA_SYSSET', [{ // name: "v_no", // type: ColumnType.STRING, @@ -445,6 +466,18 @@ struct Index { // console.log('sql error1', err) // }) if (ret) { + if (globalThis.singlePlay) { + router.pushUrl({ + url: 'pages/userInfo' + },router.RouterMode.Single) + return + } + if (globalThis.singlePlay) { + router.pushUrl({ + url: 'pages/UserInfo', + }, router.RouterMode.Single) + return + } getSyncData('MA_SYSSET').then(data => { console.log('datadata', JSON.stringify(data)) // @ts-ignore @@ -564,6 +597,7 @@ struct Index { this.num = 0 // const TcpClient: TcpClient =new TcpClient(result[0].tcplocalIp, result[0].tcplocalIpPort,result[0].tcpOppositeIp,result[0].tcpOppositePort) globalThis.lsh = '1111111111111' + } async createAlbum() { @@ -642,6 +676,7 @@ struct Index { } }, 1000) this.createAlbum() + // clearInterval(globalThis.demo) // globalThis.demo= setInterval(()=>{ // const str= {"carId":"1062","examinationRoomId":"2","videoVersion":"1.0","judgeVersion":"2023.09.30.1","shellVersion":"2023.12.13.01","host":"http://172.37.55.191:8082"} diff --git a/entry/src/main/ets/pages/Judge.ets b/entry/src/main/ets/pages/Judge.ets index c4fd91cf..19cb4f76 100644 --- a/entry/src/main/ets/pages/Judge.ets +++ b/entry/src/main/ets/pages/Judge.ets @@ -7,9 +7,9 @@ import DeductedPopup from './compontents/judge/DeductionPopup'; import AmplifyPopup from './compontents/judge/AmplifyPopup'; import Judge from './judgeSDK/judge'; import { defaultJudgeConfigObj } from './judgeSDK/utils//judgeCommon'; -import {uploadExamMileage} from '../api/judge' +import { uploadExamMileage } from '../api/judge' import DwztErrorPopup from './compontents/judge/DwztErrorPopup' -import {debounce} from '../common/utils/tools' +import { debounce } from '../common/utils/tools' import MsgPopup from './compontents/judge/MsgPopup' import { @@ -37,7 +37,7 @@ import { voiceService } from '../common/service/voiceService'; @Entry @Component struct Index { - async aboutToDisappear(){ + async aboutToDisappear() { clearInterval(this.mileageTimer) } @@ -111,8 +111,9 @@ struct Index { FLAG: carInfo.flag, BK1: carInfo.bk1, BK2: carInfo.bk2, + X_MCH: carInfo.x_mch, }) - console.info('surenjun =>carinfoArrr',JSON.stringify( this.carinfoArr)) + console.info('surenjun =>carinfoArrr', JSON.stringify(this.carinfoArr)) } // 获取考生信息 @@ -122,7 +123,7 @@ struct Index { const {xm,sfzmhm,lsh,kszp,ksdd,kssycs,kslx,ksxl,xldm} = stuInfo; this.name = xm || '测试考生'; this.idCard = sfzmhm || '01234567891010'; - this.lsh = globalThis.singlePlay?'0000000000000':lsh; + this.lsh = globalThis.singlePlay ? '0000000000000' : lsh; this.kszp = kszp; this.ksdd = ksdd; this.kssycs = kssycs; @@ -153,6 +154,7 @@ struct Index { if (Number(tempObj.markserial) > 100 && Number(tempObj.markserial) < 200) { this.manualMarkRules.push(tempObj) } + this.markRules.push(tempObj) this.markRuleListObj[`${mark.itemno}_${mark.markserial}`] = { ...tempObj, markserial: mark.markserial, @@ -189,13 +191,18 @@ struct Index { } //623 考试中是否可以查看轨迹画面(0-否+1-是) - if(sys.v_no == '623'){ - this.syssetParam623 = value == '1'?true:false + if (sys.v_no == '623') { + this.syssetParam623 = value == '1' ? true : false + } + + //386 触发模拟灯光条件 + if (sys.v_no == '386') { + this.syssetParam386 = value } //科目三应行驶距离参数 if (sys.v_no == '303') { - this.examMileage = this.examMileage == '0'?(sys.v_value + ''): this.examMileage; + this.examMileage = this.examMileage == '0' ? (sys.v_value + '') : this.examMileage; } // //地点版本参数 @@ -213,7 +220,7 @@ struct Index { const currentProject = this.projectsObj[xmdm] // 过滤考前绕车一周上车准备的扣分 - if(sczb == 1 && xmdm == '1'){ + if (sczb == 1 && xmdm == '1') { return } @@ -244,7 +251,7 @@ struct Index { //初始化systemParam表 async initSystemParam(sysParam?: SYSTEMPARMARR[]) { const systemParms: any = sysParam || await getSyncData('MA_SYSTEMPARM') - console.info('surenjun => systemParms',JSON.stringify(systemParms)); + console.info('surenjun => systemParms', JSON.stringify(systemParms)); let currentParams: any = router.getParams(); const {carName,carType,examSubject} = this; @@ -255,7 +262,7 @@ struct Index { } //真实监管下发的项目 let kStringArr: string[] = (currentParams.kString?.split(',') || []).filter(item => item); - console.info('surenjun kStringArr',JSON.stringify(kStringArr)) + console.info('surenjun kStringArr', JSON.stringify(kStringArr)) let isInExam = kStringArr.length > 0; const {isTrajectoryOpen} = judgeConfig let carNo = '', allItems = []; @@ -269,8 +276,8 @@ struct Index { systemParm.txt3 = systemParm.TXT3; } const {no1,no2,no3,} = systemParm; - const txt1 = decodeURI(systemParm.txt1) - const txt2 = decodeURI(systemParm.txt2) + const txt1 = decodeURI(systemParm.txt1) + const txt2 = decodeURI(systemParm.txt2) //获取当前考车的no2 if (no1 == 3 && no3 == 1) { if (txt1 === carName) { @@ -280,11 +287,11 @@ struct Index { } //获取及格分数线 - if(no1 == 3 && no3 == 3 && carNo === no2){ + if (no1 == 3 && no3 == 3 && carNo === no2) { this.passingScore = Number(txt1) || 0; } //根据车型获取应行驶里程数 - if(no1 == 3 && no3 ==15 && carNo === no2){ + if (no1 == 3 && no3 == 15 && carNo === no2) { this.examMileage = ((decodeURI(systemParm.txt1)) || '').split('^')[0]; } //获取当前考车的考试项目 @@ -312,20 +319,20 @@ struct Index { projectCode: no2, projectCodeCenter: txt2, //是否是必考 加减档设置成非必考 - isRequired: no2== 14 ? false : allItems.includes(no2 + ''), + isRequired: no2 == 14 ? false : allItems.includes(no2 + ''), //是否考过了 isEnd: false, //项目开始数据是否上传过 - isUpload:false, + isUpload: false, } this.projectsObj[no2*1] = currentProject this.projectsCenterObj[txt2] = currentProject this.projects.push(currentProject); //真实监管下发考试项目 - if(isInExam && !(kStringArr.includes(txt2) || kStringArr.includes(no2+''))){ - console.info('surenjun =>',txt2) - console.info('surenjun => no2',no2) + if (isInExam && !(kStringArr.includes(txt2) || kStringArr.includes(no2 + ''))) { + console.info('surenjun =>', txt2) + console.info('surenjun => no2', no2) this.projectsObj[no2*1].type = '3' this.projectsObj[no2*1].isUpload = true this.projectsObj[no2*1].isEnd = true @@ -347,7 +354,7 @@ struct Index { }) }) const projects = this.projects; - console.info('surenjun',JSON.stringify(this.ddxkKsxmArr)) + console.info('surenjun', JSON.stringify(this.ddxkKsxmArr)) if (!projects.length) { Prompt.showToast({ @@ -369,7 +376,7 @@ struct Index { const newKey = key.split('~').join('_') //@ts-ignore const xmdm = key.split('~')[0] * 1 - if(projectsObj[xmdm]){ + if (projectsObj[xmdm]) { this.cdsbInfoObj[newKey] = { kdid: cdsb.kdid, sbbh: cdsb.sbbh, @@ -384,18 +391,18 @@ struct Index { } // 获取itemInfo表信息 - async initItemInfo(){ + async initItemInfo() { const infoParams = await getSyncData('MA_ITEMINFO'); const carlist = this.carlist; const projectsObj = this.projectsObj //@ts-ignore - infoParams.forEach((info)=>{ + infoParams.forEach((info) => { const key = decodeURI(info.itemsno); const carlistArr = info.carlist === '' ? [] : (decodeURI(info.carlist).split(',') || []); const newKey = key.split('~').join('_') //@ts-ignore const xmdm = key.split('~')[0] * 1 - if(projectsObj[xmdm] && (carlistArr.length == 0 || carlistArr.includes(carlist))){ + if (projectsObj[xmdm] && (carlistArr.length == 0 || carlistArr.includes(carlist))) { this.itemInfoObj[newKey] = { modelKey: newKey, xmdm, @@ -440,7 +447,7 @@ struct Index { //断点续考 ddxkKsxmArr.forEach(xmdm => { const projectCode = this.projectsCenterObj[xmdm].projectCode - if(this.projectsObj[projectCode]){ + if (this.projectsObj[projectCode]) { this.projectsObj[projectCode].type = '3' this.projectsObj[projectCode].isUpload = true this.projectsObj[projectCode].isEnd = true @@ -549,14 +556,32 @@ struct Index { await this.initSysset(initDataObj.sysset); } + // 关闭人工扣分弹窗 + async closeDeductedPop() { + this.isDeductedPopShow = false; + this.defaultTabIndex = 0; + //上车准备&起步都开始时 + if (this.syssetParam386 == '3' + && (this.projectsObj[1].type == '2' || this.projectsObj[1].type == '3') + && this.projectsObj[2].type == '2' + && !this.syssetParam386ET3 + ) { + this.judge.rmndg = 2; + this.syssetParam386ET3 = true + } + } + // 上传考试里程 - async uploadMileage(){ - if(!globalThis.singlePlay){ + async uploadMileage() { + if (!globalThis.singlePlay) { const {lsh,startExamTime:kskssj,jl:kslc} = this const { carId ,examinationRoomId} = globalThis.carInfo; await uploadExamMileage({ - carId,examinationRoomId, - lsh,kskssj,kslc + carId, + examinationRoomId, + lsh, + kskssj, + kslc }) } } @@ -852,11 +877,13 @@ struct Index { .backgroundImageSize({ width: '100%', height: '100%' }) .margin({ bottom: 10 }) .onClick(() => { + if (this.isInitSuccess) { + this.isDeductedPopShow = true + } // this.vocObj.playAudio({ // type: 1, // name: 'button_media.wav' // }) - this.isDeductedPopShow = true }) } @@ -870,6 +897,9 @@ struct Index { Text('呼叫请求').fontColor('#FFF').fontSize(32).padding({ right: 12 }) } + .onClick(() => { + globalThis.judgeUdp.askVoice() + }) .width(334) .height(110) .justifyContent(FlexAlign.Center) @@ -920,18 +950,17 @@ struct Index { }).filter(project => project !== undefined), markRules: this.manualMarkRules, closePopup: () => { - this.isDeductedPopShow = false; - this.defaultTabIndex = 0; + this.closeDeductedPop() }, - confirmMark: async (itemno, serial)=>{ + confirmMark: async (itemno, serial) => { clearTimeout(this.popTimer) this.popTimer = null - this.popTimer = setTimeout(async ()=>{ + this.popTimer = setTimeout(async () => { const judge = this.judge await judge.setJudgeMark(itemno, serial); this.isDeductedPopShow = false this.popTimer = null; - },500) + }, 500) } }) } @@ -942,7 +971,7 @@ struct Index { showBack: false, scaleNum: 1.8, msgStr: this.judge.plcStr || '', - showTrajectory:globalThis.singlePlay ? true : (this.syssetParam623), + showTrajectory: globalThis.singlePlay ? true : (judgeConfig.isTrajectoryOpen || this.syssetParam623), }).margin({ top: 100 }) Row() { @@ -966,15 +995,15 @@ struct Index { if (this.isAmplifyPopShow && this.examSubject == 3) { AmplifyPopup({ amplifyImgIndex: this.amplifiedImgIndex, - confirmAmplify:async (amplify)=>{ + confirmAmplify: async (amplify) => { clearTimeout(this.popTimer) this.popTimer = null - this.popTimer = setTimeout(async ()=>{ + this.popTimer = setTimeout(async () => { const judge = this.judge await judge.setJudgeItem(amplify.projectCode, 1); this.isAmplifyPopShow = false this.popTimer = null; - },500) + }, 500) }, closeAmplifyPop: () => { this.isAmplifyPopShow = false @@ -990,7 +1019,7 @@ struct Index { this.endPopupVisible = false; }, confirmFn: async () => { - if(this.isErrorMsgEnd){ + if (this.isErrorMsgEnd) { this.judge.closeAllFiles() router.back() return @@ -1024,28 +1053,28 @@ struct Index { }) } - if (this.errorMsg){ + if (this.errorMsg) { MsgPopup({ title: this.errorMsg, - confirmFn:()=>{ + confirmFn: () => { this.errorMsg = '' this.isErrorMsgEnd = true; - if(this.disConnectErrorOpen){ + if (this.disConnectErrorOpen) { globalThis.context.terminateSelf() - }else{ + } else { router.back() } }, }) } - if(this.dwztErrorVisible){ + if (this.dwztErrorVisible) { DwztErrorPopup({ - title:'当前差分状态异常,学员将无法正常进行考试评判,请将车辆行驶到开阔地,等待程序自检,差分正常后会自动关闭该对话框', - cancelFn:()=>{ + title: '当前差分状态异常,学员将无法正常进行考试评判,请将车辆行驶到开阔地,等待程序自检,差分正常后会自动关闭该对话框', + cancelFn: () => { this.dwztErrorVisible = false; }, - confirmFn:()=>{ + confirmFn: () => { clearInterval(this.timer); clearInterval(globalThis.judgeTimer) this.judge.checkExamIsEnd(true); @@ -1053,7 +1082,7 @@ struct Index { }) } - if(this.disConnectErrorOpen){ + if (this.disConnectErrorOpen) { } } @@ -1090,14 +1119,14 @@ struct Index { projectsObj } = this; const projectCode = artSubject3ProjectsCodesArr[index]; - if(index === 5) { - console.info('surenjun 靠边停车状态=> ',getIsExitManualProject(index)) + if (index === 5) { + console.info('surenjun 靠边停车状态=> ', getIsExitManualProject(index)) } if (getIsExitManualProject(index)) { // 正在进行的项目 取消项目 if (isManualProjectIn && projectsObj[projectCode].type == '2') { //判断人工是否能取消项目 && 当前项目有扣分的不能取消 - if(judgeConfigObj['340'] == 1 && projectsObj[projectCode].type != '5'){ + if (judgeConfigObj['340'] == 1 && projectsObj[projectCode].type != '5') { await this.judge.setJudgeItem(projectCode, 2); Prompt.showToast({ message: '项目取消', @@ -1113,11 +1142,11 @@ struct Index { if (xmmcStr == '无' || xmmcStr == '') { //512[6] 人工项目按钮放大确认 const param512 = (judgeConfigObj['512'] || '').split(','); - console.info('surenjun',param512) - if(param512[6] !== '0'){ + console.info('surenjun', param512) + if (param512[6] !== '0') { this.amplifiedImgIndex = index; this.isAmplifyPopShow = true - }else{ + } else { const judge = this.judge await judge.setJudgeItem(projectCode, 1); } @@ -1148,7 +1177,7 @@ struct Index { getProjectIsInRoad } = this; const projectCode = artSubject3ProjectsCodesArr[index]; - if(projectsObj[projectCode] === undefined){ + if (projectsObj[projectCode] === undefined) { return false } const projectType = projectsObj[projectCode].type; @@ -1216,7 +1245,6 @@ struct Index { } return true } - // 判断项目是否在当前路段号 getProjectIsInRoad = (projectCode: string,) => { const { @@ -1244,7 +1272,7 @@ struct Index { return false } - if(projectRoads[projectCode].length == 0){ + if (projectRoads[projectCode].length == 0) { return true } @@ -1276,7 +1304,6 @@ struct Index { return true } - // 获取人工项目是否已做 getIsEndManualProject = (index: number) => { const projectName = this.artSubject3Projects[index]; @@ -1287,23 +1314,21 @@ struct Index { } return (type == '3' || type == '4') ? `${projectName}_red` : `${projectName}_green`; } - // 获取是否能进行人工评判 - getIsManualKf = () =>{ + getIsManualKf = () => { const {examSubject} = this; - if(examSubject == 3){ + if (examSubject == 3) { //杭州训练模式不允许人工评判 - if(globalThis.singlePlay && this.judgeConfigObj['211'] == 'zjhz'){ + if (globalThis.singlePlay && this.judgeConfigObj['211'] == 'zjhz') { return false } - if(this.judgeConfigObj['342'] == '0'){ + if (this.judgeConfigObj['342'] == '0') { return true } - }else{ + } else { return false } } - scroller: Scroller = new Scroller() //页面通用字体大小 @State wayno: number = 0 @@ -1364,6 +1389,9 @@ struct Index { @State serialNumber: number = 0 @State syssetParam623: boolean = false; @State syssetParam211: string = ''; + //模拟灯光触发条件 + @State syssetParam386: string = ''; + @State syssetParam386ET3: boolean = false; @State carType: string = '' @State carName: string = '' @State isDeductedPopShow: boolean = false @@ -1377,6 +1405,9 @@ struct Index { @State artSubject3Projects: string[] = ['直线', '会车', '变道', '超车', '掉头', '停车'] @State artSubject3ProjectsCodesArr: string[] = ['3', '9', '4', '10', '12', '11'] @State manualMarkRules: MarkRule[] = [] + @State markRules: MarkRule[] = [] + //页面逻辑是否初始化成功 + @State isInitSuccess: Boolean = false //科目三评判初始化数据 @State systemparmArr: SYSTEMPARMARR[] = [] @State mapPointItemArr: MAPITEMPOINTITEM[] = [] @@ -1407,8 +1438,8 @@ struct Index { @State mileageTimer: number = 0; @State passingScore: number = 80 @State dwztErrorVisible: boolean = false; - @State popTimer:number =0; - @State carlist:string= '' + @State popTimer: number = 0; + @State carlist: string = '' @State errorMsg: string = '' @State isErrorMsgEnd: boolean = false @State disConnectErrorOpen: boolean = false diff --git a/entry/src/main/ets/pages/Register.ets b/entry/src/main/ets/pages/Register.ets index ae3855c0..951c6e6b 100644 --- a/entry/src/main/ets/pages/Register.ets +++ b/entry/src/main/ets/pages/Register.ets @@ -1,11 +1,10 @@ import TopLogo from './compontents/TopLogo' import { registrationDeviceNo } from '../api/checkCar' import { dateFormat } from '../common/utils/tools' -import deviceManager from '@ohos.distributedHardware.deviceManager' -import { upDateTableByArray } from '../common/service/initable' import promptAction from '@ohos.promptAction' import FileUtil from '../common/utils/File' -import common from '@ohos.app.ability.common'; +import common from '@ohos.app.ability.common' +import deviceManager from '@ohos.distributedHardware.deviceManager' @Entry @Component @@ -24,7 +23,8 @@ export default struct Index { onPageShow() { // this.plateNo=globalThis.carInfo.plateNo console.log('createDeviceManagerstart') - try{ + try { + // @ts-ignore deviceManager.createDeviceManager('com.oh.dts', (error, value) => { if (error) { console.error('createDeviceManager failed.'); @@ -37,8 +37,8 @@ export default struct Index { globalThis.deviceNo = 'MAC-' + this.deviceNo }); - }catch (error){ - console.log('createDeviceManagererror',error) + } catch (error) { + console.log('createDeviceManagererror', error) } } @@ -125,7 +125,7 @@ export default struct Index { const folderPath = await fileUtil.initFolder(`/config`); fileUtil.addFile(`${folderPath}/deviceNo.txt`, JSON.stringify(param)) globalThis.deviceNo = this.ip - console.log('globalThis.deviceNo',globalThis.deviceNo) + console.log('globalThis.deviceNo', globalThis.deviceNo) // upDateTableByArray('DeviceInfoTable', [{ deviceId: this.ip }]) registrationDeviceNo(param).then(res => { // @ts-ignore diff --git a/entry/src/main/ets/pages/TerminalInfos.ets b/entry/src/main/ets/pages/TerminalInfos.ets index 283fe67d..dea7bf30 100644 --- a/entry/src/main/ets/pages/TerminalInfos.ets +++ b/entry/src/main/ets/pages/TerminalInfos.ets @@ -1,110 +1,199 @@ - -import TopLogo from './compontents/TopLogo' -import ethernet from '@ohos.net.ethernet'; -import prompt from '@ohos.prompt' -import { upDateTableByArray} from '../common/service/initable' -import { getSyncData} from '../common/service/initable' +import TopLogo from './compontents/TopLogo'; +import Prompt from '@system.prompt'; import FileUtil from '../common/utils/File'; import common from '@ohos.app.ability.common'; import { GlobalConfig } from '../config'; +import ethernet from '@ohos.net.ethernet' @Entry @Component struct Index { - - @State textList1: string[] = ['差分服务器Ip','响应端口','中心服务器IP','响应端口', '子网掩码','默认网关','dns','后置机IP ', '响应端口','前置机IP','本地端口'] + @State textList1: string[] = ['差分服务器Ip', '响应端口', '中心服务器IP', '响应端口', '子网掩码', '默认网关', 'dns', '后置机IP ', '响应端口', '前置机IP', '本地端口'] // @State textList2: string[] = [] @State ratio: number = 1700 / 960 - @State inputFontSize:number=12 //12 + @State inputFontSize: number = 12 //12 // // @State inputTextList1: string[] = ['192.168.7.170','8084','192.168.7.170','20122','255.255.255.0','192.168.7.1','','','114.114.114.114','112.80.35.83','11055' + // '',] // @State inputTextList2: string[] = ['192.168.7.124','20022'] // @State inputTextList1: string[] = ['172.37.55.191','18782','192.168.7.1','8082','255.255.255.0','192.168.7.170','114.114.114.114','192.168.7.124','20022','172.37.55.59','20122'] - @State inputTextList1: string[] = ['172.37.55.191','18782','172.37.55.191','8082','255.255.255.0','192.168.7.1','114.114.114.114','192.168.7.124','20022','192.168.7.170','20122'] + @State inputTextList1: string[] = ['172.37.55.191', '18782', '172.37.55.191', '8082', '255.255.255.0', '192.168.7.1', '114.114.114.114', '192.168.7.124', '20022', '192.168.7.170', '20122'] + @State terTextList: string[] = ['一型机', '二型机', '三型机', '一体机'] + @State cardTextList: string[] = ['北云', '天宝MB2'] + @State netTextList: string[] = ['否', '是'] + @State selectedTerType: number = 0 + @State selectedCardType: number = 0 + //是否启用网络差分 + @State netOpen: number = 0 // @State inputTextList2: string[] = [] // 112.80.35.83 11052 // @State inputTextList1: string[] = ['192.168.36.2','8084','192.168.36.200','20122','255.255.255.0','192.168.36.1','','','114.114.114.114','192.168.36.139','8000'] + @State @Watch('outClick') outFlag: boolean = false; + scroller: Scroller = new Scroller() // @State inputTextList2: string[] = ['192.168.36.139','20022'] private fileUtil: FileUtil private context = getContext(this) as common.UIAbilityContext; + private vocObj = null; - @State @Watch('outClick') outFlag: boolean = false; private vocObj = null; - scroller: Scroller = new Scroller() build() { Column() { - TopLogo({outFlag:$outFlag}) + TopLogo({ outFlag: $outFlag }) Column() { Column() { - Scroll(this.scroller){ - Flex({'wrap':FlexWrap.Wrap}) { - ForEach(this.textList1, (item:string, index:number) => { + Scroll(this.scroller) { + Flex({ 'wrap': FlexWrap.Wrap }) { + ForEach(this.textList1, (item: string, index: number) => { Row() { Text(item) .width('40%') .height('100%') .fontColor('#E5CBA1') - .padding({'left': '35px'}) - .fontSize(this.inputFontSize*this.ratio) - TextInput({'text':this.inputTextList1[index]?this.inputTextList1[index]: ''}) + .padding({ 'left': '35px' }) + .fontSize(this.inputFontSize * this.ratio) + TextInput({ 'text': this.inputTextList1[index] ? this.inputTextList1[index] : '' }) .width('50%') - .height('60%') + .height('50%') .fontColor('#fff') .borderColor('#E6E0D8') .borderRadius('10px') .borderWidth('2px') - .fontSize(this.inputFontSize*this.ratio) - .padding({top:0,bottom:0}) + .fontSize(this.inputFontSize * this.ratio) + .padding({ top: 0, bottom: 0 }) .linearGradient({ angle: 0, colors: [[0x403C36, 0.0], [0x4D473D, 0.34], [0x3D3A34, 1.0]] - }).onChange((value: string) => { - this.inputTextList1[index]=value + }) + .onChange((value: string) => { + this.inputTextList1[index] = value - }) - } - .width('50%') - .height('16.7%') + }) + }.width('50%').height('14%') }) + Row() {}.width('50%').height('14%') + + Row() { + Text('后置机类型') + .width('40%') + .height('100%') + .fontColor('#E5CBA1') + .padding({ 'left': '35px' }) + .fontSize(this.inputFontSize * this.ratio) + + ForEach(this.terTextList, (terText, index) => { + Radio({ value: terText, group: 'terRadioGroup' }) + .borderColor('#E5CBA1') + .checked(index === this.selectedTerType) + .onChange((value: boolean) => { + if(value){ + this.selectedTerType = index + } + }) + Text(terText).fontSize(20).fontColor('#FFF') + }) + }.width('50%').height('14%') + + + Row() { + Text('是否启用网络差分') + .width('40%') + .height('100%') + .fontColor('#E5CBA1') + .padding({ 'left': '35px' }) + .fontSize(this.inputFontSize * this.ratio) + + ForEach(this.netTextList, (netText, index) => { + Radio({ value: netText, group: 'netRadioGroup' }) + .borderColor('#E5CBA1') + .checked(index === this.netOpen) + .onChange((value: boolean) => { + if(value){ + this.netOpen = index + } + }) + Text(netText).fontSize(20).fontColor('#FFF') + }) + }.width('51%').height('14%') + + + Row(){ + Text('板卡类型') + .width('40%') + .height('100%') + .fontColor('#E5CBA1') + .padding({ 'left': '35px' }) + .fontSize(this.inputFontSize * this.ratio) + + ForEach(this.cardTextList, (cardText, index) => { + Radio({ value: cardText, group: 'cardRadioGroup' }) + .borderColor('#E5CBA1') + .checked(index === this.selectedCardType) + .onChange((value: boolean) => { + if(value){ + this.selectedCardType = index + } + }) + Text(cardText).fontSize(20).fontColor('#FFF') + }) + }.width('49%').height('14%') + } } .width('95%') - .height('90%') - .margin({'top': '2%'}) + .height('95%') + .margin({ 'top': '1%' }) .backgroundColor('#282828') .borderRadius('15px') } .width('100%') - .height('80%') + .height('85%') .borderRadius('25px') + Column() { - Image($r('app.media.terminal_save')).width('20.5%').height('74%').onClick(async ()=>{ + Image($r('app.media.terminal_save')).width('18%').onClick(async () => { const fileUtil = new FileUtil(this.context) const folderPath = await fileUtil.initFolder(`/config`); - const param={udplocalIp:this.inputTextList1[9],udplocalIpPort:this.inputTextList1[10],udpOppositeIp:this.inputTextList1[7],udpOppositeIpPort:this.inputTextList1[8],tcplocalIp:this.inputTextList1[9],tcplocalIpPort:'8088',tcpOppositeIp:this.inputTextList1[0],tcpOppositePort:this.inputTextList1[1],netMask:this.inputTextList1[4],gateway:this.inputTextList1[5],dnsServers:this.inputTextList1[6],centerIp:this.inputTextList1[2],centerPort:this.inputTextList1[3]} - fileUtil.addFile(`${folderPath}/ipConfig.txt`, JSON.stringify(param),'') + const param = { + udplocalIp: this.inputTextList1[9], + udplocalIpPort: this.inputTextList1[10], + udpOppositeIp: this.inputTextList1[7], + udpOppositeIpPort: this.inputTextList1[8], + tcplocalIp: this.inputTextList1[9], + tcplocalIpPort: '8088', + tcpOppositeIp: this.inputTextList1[0], + tcpOppositePort: this.inputTextList1[1], + netMask: this.inputTextList1[4], + gateway: this.inputTextList1[5], + dnsServers: this.inputTextList1[6], + centerIp: this.inputTextList1[2], + centerPort: this.inputTextList1[3], + terType: this.selectedTerType, + cardType: this.selectedCardType, + netOpen: this.netOpen + } + fileUtil.addFile(`${folderPath}/ipConfig.txt`, JSON.stringify(param), '') // upDateTableByArray('IpConfigTable',[]) + // @ts-ignore ethernet.setIfaceConfig("eth0", { mode: 0, - ipAddr:this.inputTextList1[9], + ipAddr: this.inputTextList1[9], route: "0.0.0.0", - gateway: this.inputTextList1[5],//value.gateway网关 - netMask: this.inputTextList1[4],//value.netMask网络掩码 + gateway: this.inputTextList1[5], //value.gateway网关 + netMask: this.inputTextList1[4], //value.netMask网络掩码 dnsServers: this.inputTextList1[6], // @ts-ignore domain: "" }, (error) => { if (error) { - prompt.showToast({ - message: '设置失败'+JSON.stringify(error), + Prompt.showToast({ + message: '设置失败' + JSON.stringify(error), duration: 3000 }); } else { - prompt.showToast({ + Prompt.showToast({ message: '设置成功', duration: 3000 }); @@ -115,21 +204,21 @@ struct Index { } .backgroundColor('#CCC4B8') .width('100%') - .height('20%') - .borderRadius({'bottomLeft':'25px','bottomRight':'25px'}) + .height('15%') + .borderRadius({ 'bottomLeft': '25px', 'bottomRight': '25px' }) .justifyContent(FlexAlign.SpaceAround) } .width('75%') - .height('69.4%') + .height('80%') .backgroundColor('#E6E3DF') .borderRadius('25px') - .margin({'top':'7%'}) + .margin({ 'top': '2%' }) .justifyContent(FlexAlign.SpaceAround) } .width('100%') .height('100%') - .backgroundImagePosition({x: 0, y: 0}) + .backgroundImagePosition({ x: 0, y: 0 }) .backgroundImage($r('app.media.index_bg')) .backgroundImageSize({ width: '100%', height: '100%' }) } @@ -138,26 +227,30 @@ struct Index { const fileUtil = new FileUtil(this.context) const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); if (data === '' || data === undefined) { - }else{ - const result=JSON.parse(data) - console.log('tagtag',JSON.stringify(result)) - this.inputTextList1[9]=result.udplocalIp - this.inputTextList1[10]=result.udplocalIpPort - this.inputTextList1[7]=result.udpOppositeIp - this.inputTextList1[8]=result.udpOppositeIpPort + } else { + const result = JSON.parse(data) + console.log('tagtag', JSON.stringify(result)) + this.inputTextList1[9] = result.udplocalIp + this.inputTextList1[10] = result.udplocalIpPort + this.inputTextList1[7] = result.udpOppositeIp + this.inputTextList1[8] = result.udpOppositeIpPort - // this.inputTextList1[0]=result[0].tcplocalIp - // this.inputTextList1[13]=result[0].tcplocalIpPort - this.inputTextList1[0]=result.tcpOppositeIp - this.inputTextList1[1]=result.tcpOppositePort - this.inputTextList1[5]=result.gateway - this.inputTextList1[4]=result.netMask - this.inputTextList1[6]=result.dnsServers - this.inputTextList1[2]=result.centerIp - this.inputTextList1[3]=result.centerPort + // this.inputTextList1[0]=result[0].tcplocalIp + // this.inputTextList1[13]=result[0].tcplocalIpPort + this.inputTextList1[0] = result.tcpOppositeIp + this.inputTextList1[1] = result.tcpOppositePort + this.inputTextList1[5] = result.gateway + this.inputTextList1[4] = result.netMask + this.inputTextList1[6] = result.dnsServers + this.inputTextList1[2] = result.centerIp + this.inputTextList1[3] = result.centerPort + this.selectedTerType = result.terType + this.selectedCardType = result.cardType + this.netOpen= result.netOpen + console.log('surenjun', this.selectedTerType + ''); } - + //@ts-ignore ethernet.getIfaceConfig("eth0", (error, value) => { if (error) { // that.errorMsg='error' @@ -173,10 +266,12 @@ struct Index { }) } + onPageShow() { console.info('Index onPageShow'); } - outClick(){ + + outClick() { } } \ No newline at end of file diff --git a/entry/src/main/ets/pages/UserInfo.ets b/entry/src/main/ets/pages/UserInfo.ets index 7138850e..16f2a14a 100644 --- a/entry/src/main/ets/pages/UserInfo.ets +++ b/entry/src/main/ets/pages/UserInfo.ets @@ -89,6 +89,8 @@ struct UserInfo { 'Param830Str': '0', //同一学员连续第二次考试时不再验证身份 'Param364': '0', //考前上车准备 'Param398': '0', //考前上车准备 + 'Param835': '0', //考前上车准备 + 'Param850': '0', //考前上车准备 } @State startExam: boolean = false // 过程照片拍照 @@ -141,9 +143,11 @@ struct UserInfo { this.sfbdinterfaceFn() } else { this.showFaceCompare = true + this.ksksLimit = false } } else { this.sfbdinterfaceFn() + this.ksksLimit = false } } catch (e) { console.info('Throw Error', JSON.stringify(e)) @@ -159,6 +163,7 @@ struct UserInfo { cancel: () => { }, confirm: () => { + this.prePareExam() } }), customStyle: true, @@ -200,57 +205,80 @@ struct UserInfo { // this.openDeviceByIDCard() const routerParam = router.getParams() || { type: 0 }; console.log('routerParam', JSON.stringify(routerParam)) - + initJudgeUdp() if (!globalThis.singlePlay) { // @ts-ignore if (routerParam.type != 1) { + console.info('surenjun','Judge返回到UserInfo界面') // @ts-ignore this.list = await getSyncData('USERLIST') // @ts-ignore const data = await getSyncData('USER') - console.log('useruser,', JSON.stringify(this.list)) - console.log('useruser1,', JSON.stringify(data)) + console.log('surenjun useruser=>,', JSON.stringify(this.list)) + console.log('surenjun useruser1=>,', JSON.stringify(data)) const user = data[0] - if (user && Number(user.kssycs)) { - let flag = false - this.list.forEach(res => { - if (res.sfzmhm == user.sfzmhm) { - flag = true - res.kssycs = user.kssycs - this.getCurrentStudent(res.sfzmhm) - } - }) - if (!flag) { - this.currentUser = (this.list.length ? this.list[0] : EmptyCandidateObject) - } - } else if (user && (user.kssycs == '0' || user.kssycs == '')) { - console.log('datadatadatadata') + if(!Number(user.kssycs)){ this.list = this.list.filter(res => { return res.sfzmhm != user.sfzmhm }) - this.pageIndex = 0 - this.dataList = this.list.slice(this.pageIndex * 4, this.pageIndex * 4 + 4) - if (this.dataList.length) { - setTimeout(() => { - this.currentUser = this.dataList[0] - this.currentUser.ksy2 = globalThis.kgxm - globalThis.lsh = this.currentUser.lsh - }, 200) - } else { - this.currentUser = EmptyCandidateObject - } + } + this.pageIndex = 0 + this.dataList = this.list.slice(this.pageIndex * 4, this.pageIndex * 4 + 4) + if (this.dataList.length) { + setTimeout(() => { + this.currentUser = this.dataList[0] + this.currentUser.ksy2 = globalThis.kgxm + globalThis.lsh = this.currentUser.lsh + }, 200) + } else { + this.currentUser = EmptyCandidateObject + globalThis.lsh = '1111111111111' } this.list.forEach((res, index) => { res.id = index.toString() }) await upDateTableByArray('USERLIST', this.list || []) + + // if(this.) + // if (user && Number(user.kssycs)) { + // + // let flag = false + // this.list.forEach(res => { + // if (res.sfzmhm == user.sfzmhm) { + // flag = true + // res.kssycs = user.kssycs + // this.getCurrentStudent(res.sfzmhm) + // } + // }) + // if (!flag) { + // this.currentUser = (this.list.length ? this.list[0] : EmptyCandidateObject) + // globalThis.lsh = this.list.length?this.currentUser.lsh:'1111111111111' + // } + // } else if (user && (user.kssycs == '0' || user.kssycs == '')) { + // console.log('datadatadatadata') + // this.list = this.list.filter(res => { + // return res.sfzmhm != user.sfzmhm + // }) + // this.pageIndex = 0 + // this.dataList = this.list.slice(this.pageIndex * 4, this.pageIndex * 4 + 4) + // if (this.dataList.length) { + // setTimeout(() => { + // this.currentUser = this.dataList[0] + // this.currentUser.ksy2 = globalThis.kgxm + // globalThis.lsh = this.currentUser.lsh + // }, 200) + // } else { + // this.currentUser = EmptyCandidateObject + // globalThis.lsh = '1111111111111' + // } + // } + } else { await this.getExaminationStudentInfoFn() } } - // 如果是单机模式则模拟假数据 //获取sysset表数据 this.initSysset() @@ -263,8 +291,6 @@ struct UserInfo { // this.currentUser=user // } this.sczbkf = []; - initJudgeUdp() - //监听远程开始考试 globalThis.udpEvent.onBeginExam(async () => { console.info('surenjun', 'userInfo收到UdpEvent事件') @@ -339,7 +365,6 @@ struct UserInfo { setTimeout(() => { this.currentUser = this.list[0] this.currentUser.ksy2 = globalThis.kgxm - globalThis.lsh = this.currentUser.lsh }, 200) @@ -512,6 +537,13 @@ struct UserInfo { if (sys.v_no === '770') { that.systemParam.Param770Str = sys.v_value; } + if (sys.v_no === '835') { + that.systemParam.Param835 = sys.v_value; + } + //盲考 + if (sys.v_no === '850') { + that.systemParam.Param850 = sys.v_value; + } // 开始考试前必须解开安全带或关车门 if (sys.v_no === '803') { that.systemParam.Param803Str = sys.v_value + ''; @@ -641,8 +673,7 @@ struct UserInfo { this.startExam = false // await upDateTableByArray('USER', []) // await upDateTableByArray('USERLIST', []) - await DB.clearTable('USER') - await DB.clearTable('USERLIST') + this.type = '2' this.errorDialog.open() this.updateTimeLimit = true @@ -650,6 +681,8 @@ struct UserInfo { try { getExaminationStudentInfo(param).then(async (res) => { console.log("temp log ", JSON.stringify(res)) + await DB.clearTable('USER') + await DB.clearTable('USERLIST') this.errorDialog.close() setTimeout(() => { this.updateTimeLimit = false @@ -714,23 +747,24 @@ struct UserInfo { return res.kssycs == '1' }) if (this.dataList.length) { - if (user.length) { - setTimeout(() => { - this.currentUser = user[0] - this.currentUser.ksy2 = globalThis.kgxm - globalThis.lsh = this.currentUser.lsh - globalThis.ksyh = this.currentUser.ksy1sfzmhm - }, 200) - } else { - setTimeout(() => { - this.currentUser = this.dataList[0] - this.currentUser.ksy2 = globalThis.kgxm - globalThis.ksyh = this.currentUser.ksy1sfzmhm - globalThis.lsh = this.currentUser.lsh - }, 200) - } + // if (user.length) { + // setTimeout(() => { + // this.currentUser = user[0] + // this.currentUser.ksy2 = globalThis.kgxm + // globalThis.lsh = this.currentUser.lsh + // globalThis.ksyh = this.currentUser.ksy1sfzmhm + // }, 200) + // } else { + setTimeout(() => { + this.currentUser = this.dataList[0] + this.currentUser.ksy2 = globalThis.kgxm + globalThis.ksyh = this.currentUser.ksy1sfzmhm + globalThis.lsh = this.currentUser.lsh + }, 200) + // } } else { this.currentUser = EmptyCandidateObject + globalThis.lsh = '1111111111111' } @@ -851,6 +885,7 @@ struct UserInfo { //身份比对 async sfbdinterfaceFn() { globalThis.statue = 4 + this.ksksLimit = false this.stepFlag = true const carInfo = globalThis.carInfo; const {carId,examinationRoomId} = carInfo; @@ -1108,12 +1143,12 @@ struct UserInfo { CommText({ ratio: this.ratio, color: item.sfzmhm != this.currentUser.sfzmhm ? '#FFFFFF' : '#000000', - text: item.lsh + text: this.systemParam.Param850&&Number(this.systemParam.Param850)>0?"*****":item.lsh }) CommText({ ratio: this.ratio, color: item.sfzmhm != this.currentUser.sfzmhm ? '#FFFFFF' : '#000000', - text: decodeURIComponent(item.xm) + text: this.systemParam.Param850&&Number(this.systemParam.Param850)>0?"*****":decodeURIComponent(item.xm) }) } } @@ -1123,7 +1158,7 @@ struct UserInfo { .backgroundImageSize({ width: '100%', height: '100%' }) .onClick(() => { console.log('this.startExam', this.startExam, this.systemParam.Param364, this.isExamStart) - if ((this.isExamStart && !globalThis.singlePlay && this.systemParam.Param341) || (this.startExam && this.systemParam.Param364 == '2')) { + if (this.startExam && this.systemParam.Param364 == '2') { return } this.currentUser = EmptyCandidateObject @@ -1182,7 +1217,42 @@ struct UserInfo { Column() { ForEach(this.labelBlocks, (item) => { - LabelBlock({ label: item.label, ratio: this.ratio, value: this.currentUser[item.key] }) + if(this.systemParam.Param850=='1'){ + LabelBlock({ label: item.label, ratio: this.ratio, value:'*****'}) + } + else if(this.systemParam.Param850=='2'){ + if(item.key=='xm'){ + LabelBlock({ label: item.label, ratio: this.ratio, value: this.currentUser.xh }) + }else if(item.key=='ksxl'){ + LabelBlock({ label: item.label, ratio: this.ratio, value: this.currentUser[item.key] }) + }else{ + LabelBlock({ label: item.label, ratio: this.ratio, value: '*****' }) + } + }else if(this.systemParam.Param850=='4'){ + if(item.key=='ksxl'){ + LabelBlock({ label: item.label, ratio: this.ratio, value: '*****' }) + }else{ + LabelBlock({ label: item.label, ratio: this.ratio, value: this.currentUser[item.key] }) + } + }else if(this.systemParam.Param850=='5'){ + if(item.key=='xm'){ + LabelBlock({ label: item.label, ratio: this.ratio, value: this.currentUser.xh }) + }else{ + LabelBlock({ label: item.label, ratio: this.ratio, value: '*****' }) + } + }else if(this.systemParam.Param850=='6'){ + if(item.key=='ksxl'||item.key=='kssycs'){ + LabelBlock({ label: item.label, ratio: this.ratio, value: this.currentUser[item.key] }) + }else if(item.key=='sfzmhm'){ + LabelBlock({ label: item.label, ratio: this.ratio, value: this.currentUser.sfzmhm.slice(-6) }) + }else{ + LabelBlock({ label: item.label, ratio: this.ratio, value: '*****' }) + } + } + else{ + LabelBlock({ label: item.label, ratio: this.ratio, value: this.currentUser[item.key] }) + + } }) } } @@ -1197,6 +1267,9 @@ struct UserInfo { // .commStyle() imageBtn({ btnWidth: 220 * this.ratio, btnHeight: 69 * this.ratio, imgSrc: $r('app.media.yydj_btn') }) .margin({ bottom: 12 * this.ratio }) + .onClick(()=>{ + globalThis.judgeUdp.askVoice() + }) // Image($r('app.media.gx_btn')) // .commStyle() @@ -1245,6 +1318,13 @@ struct UserInfo { if (this.systemParam.Param612Str == '1') { return } + if(!globalThis.singlePlay&&Number(this.systemParam.Param835)&&Number(this.currentUser.yycs)&&Number(this.systemParam.Param835)<=Number(this.currentUser.yycs)){ + this.type='4' + this.title='当前考生预约考试次数为'+this.currentUser.yycs + this.errorDialog.open() + return + } + await this.prePareExam() }) } @@ -1400,4 +1480,6 @@ type systemParam = { 'Param830Str': string, //同一学员连续第二次考试时不再验证身份 'Param364': string, //考前上车准备 'Param398': string, //考前上车准备 + 'Param835': string, //考前上车准备 + 'Param850': string, //考前上车准备 } \ No newline at end of file diff --git a/entry/src/main/ets/pages/VideoConfig.ets b/entry/src/main/ets/pages/VideoConfig.ets index ec554df6..a5c186bf 100644 --- a/entry/src/main/ets/pages/VideoConfig.ets +++ b/entry/src/main/ets/pages/VideoConfig.ets @@ -117,7 +117,7 @@ struct Index { for (let i = 1; i <= 4; i++) { console.log('rocord_handle', i, JSON.stringify(this.rocordHandleObj)) if (this.rocordHandleObj['rocord_handle'+i]) { - endRecordVideo(this.rocordHandleObj['rocord_handle'+i]) + endRecordVideo(this.rocordHandleObj) this.rocordHandleObj['rocord_handle'+i] = 0 } } diff --git a/entry/src/main/ets/pages/compontents/FaceCompare.ets b/entry/src/main/ets/pages/compontents/FaceCompare.ets index 254fef4b..74835c59 100644 --- a/entry/src/main/ets/pages/compontents/FaceCompare.ets +++ b/entry/src/main/ets/pages/compontents/FaceCompare.ets @@ -44,8 +44,7 @@ export default struct FaceCompare { build() { Column() { Column() { - Text('照片比对') - // .lineHeight('16%') + Text('照片比对')// .lineHeight('16%') .height('16%') .fontWeight(FontWeight.Bold) .fontSize(24) @@ -81,8 +80,7 @@ export default struct FaceCompare { .height('52%') .justifyContent(FlexAlign.SpaceBetween) - Text('正在等待拍照…') - // .lineHeight('16%') + Text('正在等待拍照…')// .lineHeight('16%') .height('16%') .fontWeight(FontWeight.Bold) .fontColor('#CC7E00') @@ -184,21 +182,20 @@ export default struct FaceCompare { async faceComparFn() { console.log('mmmmm0', 2) - this.param.pztd=this.param.rlls - const data=await takePhoto(this.param, this.context, 'jt/', 1,) - this.base64=this.imageBase64 + data.base64 - console.log('mmmmt',this.base64) + this.param.pztd = this.param.rlls + const data = await takePhoto(this.param, this.context, 'jt/', 1,) + this.base64 = this.imageBase64 + data.base64 faceCompare({ sfzh: this.sfzh, - firstImage: this.firstImage.substr(22), - secondImage: data.base64, + secondImage: this.firstImage.substr(22), + firstImage: data.base64, type: 2, verifyType: 1 }) .then(res => { console.log('mmmmm8', JSON.stringify(res)) // @ts-ignore - if (res.imageCompareRsp.head.resultCode=='0') { + if (res.imageCompareRsp.head.resultCode == '0') { this.controller.stop() this.showFaceCompare = !this.showFaceCompare this.showFaceCompareFlag = !this.showFaceCompareFlag @@ -217,7 +214,15 @@ export default struct FaceCompare { }) } + }).catch((err) => { + console.log(err) + this.times++; + //3s后开始语音提示 + this.vocObj.playAudio({ + type: 1, + name: 'face_fail.mp3' }) + }) console.log('mmmmm8', 9) @@ -226,7 +231,7 @@ export default struct FaceCompare { async heartMsg(context) { let tmpList = [] const str = this.lsh - console.log('this.lshbitbit',this.lsh,globalThis.carInfo.carNo,globalThis.carInfo.examinationRoomId) + console.log('this.lshbitbit', this.lsh, globalThis.carInfo.carNo, globalThis.carInfo.examinationRoomId) for (let i = 0; i < str.length; i++) { tmpList.push(string2Bytes(str.charCodeAt(i), 1 * 8)[0]) } @@ -253,8 +258,8 @@ export default struct FaceCompare { } }, 1000) globalThis.udpClient2.setMsgCallBack((val) => { - console.log('valvalval',globalThis.statue,JSON.stringify(val)) - if(globalThis.statue!=3){ + console.log('valvalval', globalThis.statue, JSON.stringify(val)) + if (globalThis.statue != 3) { return } if (val.id == '48') { diff --git a/entry/src/main/ets/pages/compontents/SignDisplayCom.ets b/entry/src/main/ets/pages/compontents/SignDisplayCom.ets index 60dbe634..b076d3be 100644 --- a/entry/src/main/ets/pages/compontents/SignDisplayCom.ets +++ b/entry/src/main/ets/pages/compontents/SignDisplayCom.ets @@ -293,10 +293,13 @@ export default struct SignDisplayCom { .margin({ top: 6 * this.ratio, left: 10 * this.ratio }) Row() { - RealTime({ - widthNumber: Math.floor(550 * this.ratio), - heightNumber: Math.floor(380 * this.ratio), - }) + if(this.active == 1) { + RealTime({ + widthNumber: Math.floor(550 * this.ratio), + heightNumber: Math.floor(380 * this.ratio), + }) + } + } .width(550 * this.ratio) .height(380 * this.ratio) @@ -422,7 +425,9 @@ export default struct SignDisplayCom { const str2=this.signArr[93].substr(4.2) this.signArr[93]=str2+str1+str0 this.GPSColum[10].value = this.signArr[93] - + const hours=Number(this.signArr[94].substr(0,2))+8 + this.signArr[94]=(hours>9?hours:'0'+hours)+this.signArr[94].substr(2,this.signArr[94].length-2) + // this.signArr[53]=192.168.7.170' // this.signArr[53]=192.168.7.170' this.sjxhColum = JSON.parse(JSON.stringify((this.sjxhColum))) that.signArr = JSON.parse(JSON.stringify((this.signArr))) diff --git a/entry/src/main/ets/pages/compontents/errorMsgDialog.ets b/entry/src/main/ets/pages/compontents/errorMsgDialog.ets index b28392bb..26cc3958 100644 --- a/entry/src/main/ets/pages/compontents/errorMsgDialog.ets +++ b/entry/src/main/ets/pages/compontents/errorMsgDialog.ets @@ -46,17 +46,17 @@ export default struct errorMsgDialog { Row() { Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Text(' 取 消 ') - .fontSize(24 * globalThis.ratio* this.dialogRatio*0.6 ) + .fontSize(24 * globalThis.ratio * this.dialogRatio * 0.6) .fontColor('#fff') - .width(60 * globalThis.ratio* this.dialogRatio) + .width(60 * globalThis.ratio * this.dialogRatio) } .commStyle() .onClick(() => { if (this.controller != undefined) { - const errorCode=AppStorage.Get('errorMsg'); + const errorCode = AppStorage.Get('errorMsg'); // const errorCodeFlage=AppStorage.Get('errorCodeFlage'); // console.log('errorCode',errorCode,errorCodeFlage) - if(errorCode==0){ + if (errorCode == 0) { router.replaceUrl({ url: 'pages/Index', }, router.RouterMode.Single); @@ -66,64 +66,92 @@ export default struct errorMsgDialog { this.cancel() this.controller.close() } - }).margin({ right: 10 * globalThis.ratio * this.dialogRatio}) + }).margin({ right: 10 * globalThis.ratio * this.dialogRatio }) Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { Text(' 确 定 ') - .fontSize(24 * globalThis.ratio* this.dialogRatio*0.6) + .fontSize(24 * globalThis.ratio * this.dialogRatio * 0.6) .fontColor('#fff') - .width(60 * globalThis.ratio* this.dialogRatio) + .width(60 * globalThis.ratio * this.dialogRatio) } .commStyle() .onClick(() => { - const errorCode=AppStorage.Get('errorCode'); - const errorCodeFlage=AppStorage.Get('errorCodeFlage'); - console.log('errorCode',errorCode,errorCodeFlage) - if(errorCode==0&&errorCodeFlage){ - router.replaceUrl({ - url: 'pages/Index', - }, router.RouterMode.Single); - router.clear(); + const errorCode = AppStorage.Get('errorCode'); + const errorCodeFlage = AppStorage.Get('errorCodeFlage'); + console.log('errorCode', errorCode, errorCodeFlage) + if (errorCode == 0 && errorCodeFlage) { + router.replaceUrl({ + url: 'pages/Index', + }, router.RouterMode.Single); + router.clear(); - } - console.log('errorCode',errorCode,errorCodeFlage) + } + console.log('errorCode', errorCode, errorCodeFlage) - if (this.controller != undefined){ + if (this.controller != undefined) { this.confirm() this.controller.close() } - } + } - ) + ) + } + + .padding({ bottom: 20 }) + } + if (this.type == '4') { + Flex({ justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { + Text(' 确 定 ') + .fontSize(24 * globalThis.ratio * this.dialogRatio * 0.6) + .fontColor('#fff') + .width(60 * globalThis.ratio * this.dialogRatio) + } + .commStyle() + .onClick(() => { + const errorCode = AppStorage.Get('errorCode'); + const errorCodeFlage = AppStorage.Get('errorCodeFlage'); + console.log('errorCode', errorCode, errorCodeFlage) + if (errorCode == 0 && errorCodeFlage) { + router.replaceUrl({ + url: 'pages/Index', + }, router.RouterMode.Single); + router.clear(); + + } + console.log('errorCode', errorCode, errorCodeFlage) + + if (this.controller != undefined) { + this.confirm() + this.controller.close() + } + } + + ) + } + } + .backgroundColor('#E6E3DF') + .borderRadius(19 * globalThis.ratio) + .constraintSize({ minWidth: 520 }) } - .padding({bottom:20}) -} -} -. -backgroundColor('#E6E3DF') - .borderRadius(19 * globalThis.ratio) - .constraintSize({ minWidth: 520 }) -} - -aboutToAppear() { - AppStorage.SetOrCreate('errorMsg', 0); - setTimeout(() => { - console.log('this.type', this.type, this.angle) - if (this.type == '2') { - this.angle = 360 - } - }, 1000) - if (this.type == '1') { + aboutToAppear() { + AppStorage.SetOrCreate('errorMsg', 0); setTimeout(() => { - this.controller.close() - }, 2000) + console.log('this.type', this.type, this.angle) + if (this.type == '2') { + this.angle = 360 + } + }, 1000) + if (this.type == '1') { + setTimeout(() => { + this.controller.close() + }, 2000) + } } -} -aboutToDisappear() { - this.title = '' - this.angle = 0 - AppStorage.SetOrCreate('errorCodeFlage', false); -} + aboutToDisappear() { + this.title = '' + this.angle = 0 + AppStorage.SetOrCreate('errorCodeFlage', false); + } } \ No newline at end of file diff --git a/entry/src/main/ets/pages/compontents/judge/RealTime.ets b/entry/src/main/ets/pages/compontents/judge/RealTime.ets index a31e8832..51fea143 100644 --- a/entry/src/main/ets/pages/compontents/judge/RealTime.ets +++ b/entry/src/main/ets/pages/compontents/judge/RealTime.ets @@ -3,8 +3,9 @@ import Judge from '../../judgeSDK/utils/judgeReal'; import { MarkRule, Project, ProjectObj } from '../../judgeSDK/api/judgeSDK.d'; import common from '@ohos.app.ability.common'; import { - examJudgeMapSetScaling + examJudgeMapSetScaling, examJudgeVersion } from '../../judgeSDK/api' +import { judgeConfig } from '../../judgeSDK/utils/judgeConfig'; interface RoadDataType { name: string, @@ -30,6 +31,8 @@ export default struct RealTime { @State ratio: number = 1 @State lane: Object = {} @State timer:number = 0 + @State version: string = "" + constructor() { super() @@ -67,22 +70,28 @@ export default struct RealTime { Column() { if (this.draw) { - XComponent({ - id: 'duolun_plugin_id_draw', //显示轨迹窗口id名称,注意这个ID要和C++侧一致,不能变 - type: 'surface', - libraryname: 'JudgeSdk' - // libraryname: 'judgesdk' - }) - .width(this.widthNumber) - .height(this.heightNumber) - .onLoad(() => { - apiJudgeSdk.examJudgeMapSetDrawing(true); //停止绘制地图轨迹,false:表示结束绘制 - }) - .onDestroy(() => { - apiJudgeSdk.examJudgeMapSetDrawing(false); //停止绘制地图轨迹,false:表示结束绘制 - this.draw = false; - clearInterval(globalThis.realTimer) + Stack({ alignContent: Alignment.TopEnd }) { + XComponent({ + id: 'duolun_plugin_id_draw', //显示轨迹窗口id名称,注意这个ID要和C++侧一致,不能变 + type: 'surface', + libraryname: 'JudgeSdk' }) + .width(this.widthNumber) + .height(this.heightNumber) + .onLoad(() => { + apiJudgeSdk.examJudgeMapSetDrawing(true); //停止绘制地图轨迹,false:表示结束绘制 + }) + .onDestroy(() => { + apiJudgeSdk.examJudgeMapSetDrawing(false); //停止绘制地图轨迹,false:表示结束绘制 + this.draw = false; + clearInterval(globalThis.realTimer) + }) + + }.width(this.widthNumber) + .height(this.heightNumber) + Row() { + Text(this.version).margin({ right: 10 }).fontSize(14).fontColor(0x333333) + } } else { Column() { } @@ -108,7 +117,10 @@ export default struct RealTime { async aboutToDisappear() { clearInterval(this.timer) } + async aboutToAppear() { + this.version = (await examJudgeVersion()) + "/" + judgeConfig.version + const judge = new Judge(this) let timer = setInterval(()=>{ this.lane = globalThis.laneData; diff --git a/entry/src/main/ets/pages/judgeSDK/api/judgeSDK.d.ts b/entry/src/main/ets/pages/judgeSDK/api/judgeSDK.d.ts index f398950e..b953d198 100644 --- a/entry/src/main/ets/pages/judgeSDK/api/judgeSDK.d.ts +++ b/entry/src/main/ets/pages/judgeSDK/api/judgeSDK.d.ts @@ -73,6 +73,8 @@ export interface CARINFO { FLAG: string, BK1: string, BK2: string + //脉冲里程设置 + X_MCH: string } export interface MAPPOINT { diff --git a/entry/src/main/ets/pages/judgeSDK/judge.ts b/entry/src/main/ets/pages/judgeSDK/judge.ts index 2291d3bf..0766fafe 100644 --- a/entry/src/main/ets/pages/judgeSDK/judge.ts +++ b/entry/src/main/ets/pages/judgeSDK/judge.ts @@ -15,6 +15,7 @@ import { uploadExamProgressData, writeObjectOut } from '../../api/judge'; import UsbService from '../../common/service/usbService'; import { KF, LANE } from '../judgeSDK/api/judgeSDK.d'; import { endRecordVideo, saveStartRecordVideo } from '../../common/service/videoService'; + import { Array2Byte, convertGpsCoord2, @@ -54,9 +55,16 @@ import { examJudgeVersion } from './api/index'; import { getSyncData, upDateTableByArray } from '../../common/service/initable'; - +import { GlobalConfig } from '../../config'; const judgeTag = 'SURENJUN_JUDGE' +function ifNeedRetry(code: number | string): boolean { + let arr = ["B210010", "B210023", "B210024", "B210031", "B210033", "B210034", "B210041"] + if (!arr.includes(code + "") && code != 1) { + return true + } + return false +} export default class Judge { // 过程照片拍照 getPhoto = async (empty?: boolean) => { @@ -158,8 +166,8 @@ export default class Judge { map_point_item: mapPointItemArr, //科目三暂时为空 iteminfo: [], - roads: getModelData('km3/Roads.txt'), - sharps: getModelData('km3/Sharps.txt') + roads: getModelData('Roads.txt'), + sharps: getModelData('Sharps.txt') } } // 处理特殊参数配置 @@ -232,7 +240,6 @@ export default class Judge { } // 处理udp plc信号 handleUdp = async (msg) => { - console.info('plc信号', msg) const {fileLog,getPlcData,usbService,isUdpEnd,isExamEnd,judgeUI} = this const stachArr = msg.split(',') if (stachArr[0] != '#DN_GD' || isUdpEnd) { @@ -253,20 +260,23 @@ export default class Judge { this.judgeUI.dw = (Math.floor(plcData.sensor.dw as number) || 0) + '' //TODO 暂时关闭差分检测异常 // await this.checkDwzt(plcData.gps.dwzt,plcData.gps.jdzt); - if (!isExamEnd) { - await examJudgeRealExam(plcData) - } const udpIndex = globalThis.udpIndex; - let [prevJd, preWd] = [0, 0] if (udpIndex % 5 === 0 && !isUdpEnd) { const judgeUdp = globalThis.judgeUdp const bytes = await this.getMessageHeartbeat(isExamEnd); judgeUdp.send(bytes) } + if (!isExamEnd) { + console.info(judgeTag, 'start examJudgeRealExam') + await examJudgeRealExam(plcData) + console.info(judgeTag, 'end examJudgeRealExam') + } + let [prevJd, preWd] = [0, 0] globalThis.udpIndex += 1 } private fileLog private filePath + private bklx: number = 0 private totalScore: number private prevJd: number = 0 private prevWd: number = 0 @@ -275,7 +285,7 @@ export default class Judge { private modelPath: string private avPlayer private carztStr: string - private rmndg: 0 | 1 + private rmndg: 0 | 1 | 2 private mndgStr: string | undefined // 模拟灯光 setMndg = async (mndgStr: string) => { @@ -309,7 +319,7 @@ export default class Judge { const tJD = convertGpsCoord2(jd) const tWD = convertGpsCoord2(wd) const {prevJd,prevWd} = this - if (prevJd && dwzt == 4 && jdzt == 3) { + if (prevJd && dwzt == 4 && jdzt == 3 && !globalThis.singlePlay) { const distance = await examCalcGpsDistance({ jd1: prevJd, wd1: prevWd, @@ -318,7 +328,7 @@ export default class Judge { h: hxj || 1, }) //@ts-ignore - globalThis.distanceClass?.setTimeData(((distance / 100).toFixed(2)) * 1) + // globalThis.distanceClass?.setTimeData(((distance / 100).toFixed(2)) * 1) } this.prevJd = tJD; this.prevWd = tWD; @@ -326,12 +336,13 @@ export default class Judge { private performInfo: any private isEndTip: boolean = false; private deductedPopShowTimer: number = 0; + // 校验考试是否结束 checkExamIsEnd = async (isManual?: boolean) => { const {judgeUI,avPlayer,isExamEnd,isEndTip,ksjs} = this; const {isAllProjectsEnd,examSubject,singlePlay,totalScore,judgeConfigObj,passingScore,examMileage,jl} = judgeUI; - + const param302 = judgeConfigObj['302']; if (isExamEnd) { return } @@ -343,10 +354,8 @@ export default class Judge { this.isExamEnd = true this.isManual = true } else { - const param302 = judgeConfigObj['302']; const param342 = judgeConfigObj['342']; const param512 = (judgeConfigObj['512'] || '').split(','); - //单机模式 if (singlePlay) { console.info(judgeTag + ' isAllProjectsEnd => ', isAllProjectsEnd) @@ -355,11 +364,11 @@ export default class Judge { if (totalScore >= passingGrade && !isEndTip) { if (examSubject == 3 && (param342 == 0 || param342 == 2) && (param302 != 6 || param302 != 7 || param302 != 8)) { if (param512[7] != 0) { - clearTimeout(this.deductedPopShowTimer) - avPlayer.playAudio(['voice/综合评判.mp3']) - this.judgeUI.isDeductedPopShow = true - this.judgeUI.defaultTabIndex = 1 - this.isEndTip = true + // clearTimeout(this.deductedPopShowTimer) + // avPlayer.playAudio(['voice/综合评判.mp3']) + // this.judgeUI.isDeductedPopShow = true + // this.judgeUI.defaultTabIndex = 1 + // this.isEndTip = true return } } else { @@ -381,15 +390,17 @@ export default class Judge { //成绩不合格 if (totalScore < passingGrade) { //科目三不合格报靠边停车 - if (examSubject == 3 && param302 == 1) { - avPlayer.playAudio([`voice/考试结束.mp3`]); - return + if (examSubject == 3 ) { + if( param302 == 1){ + avPlayer.playAudio([`voice/考试结束.mp3`]); + }else if(param302 == 0){ + return + } } await examJudgeEndExam() this.isExamEnd = true return } - //成绩合格 if (isAllProjectsEnd && totalScore >= passingGrade && !isEndTip) { if (examSubject == 2) { @@ -412,12 +423,12 @@ export default class Judge { if (examSubject == 3 && (param342 == 0 || param342 == 2) && (param302 != 6 || param302 != 7 || param302 != 8)) { if (param512[7] != 0) { - clearTimeout(this.deductedPopShowTimer) - this.judgeUI.isDeductedPopShow = false - avPlayer.playAudio(['voice/综合评判.mp3']) - this.judgeUI.isDeductedPopShow = true - this.judgeUI.defaultTabIndex = 1 - this.isEndTip = true + // clearTimeout(this.deductedPopShowTimer) + // this.judgeUI.isDeductedPopShow = false + // avPlayer.playAudio(['voice/综合评判.mp3']) + // this.judgeUI.isDeductedPopShow = true + // this.judgeUI.defaultTabIndex = 1 + // this.isEndTip = true } } else { await examJudgeEndExam() @@ -508,11 +519,14 @@ export default class Judge { if (msg.method === 'examJudgeArtificialMark') { setJudgeItem(msg.itemno, msg.serial) } + msg.sensor.rmndg = this.rmndg + await fileLog.setExamJudgeData(msg) await examJudgeRealExam(msg) + this.rmndg = 0 const bytes = await this.getMessageHeartbeat(); bytes && globalThis.judgeUdp.send(bytes) - }, 200) + }, 50) globalThis.judgeTimer = judgeTimer; } @@ -598,14 +612,25 @@ export default class Judge { } private videoData: any private disConnectNum: number = 0; + //调用监管接口 + //调用监管接口 sendWriteObjectOut = async (data, filePath) => { const temp = await writeObjectOut(data, filePath); console.log("wzj", JSON.stringify(temp)) - //断网&网络超时次数计算 - if (temp.code == 2300007 || temp.code == 2300028) { + if (this.disConnectNum == 0) { + console.log("wzj", "第一次发送", JSON.stringify(data)) + } + if (this.disConnectNum < 5 && this.disConnectNum > 0) { + console.log("wzj", "第" + this.disConnectNum + "次重新发送", JSON.stringify(data)) + } + // 不是成功的接口就需要补传 + if (ifNeedRetry(temp.code)) { this.disConnectNum += 1; if (this.disConnectNum < 5) { + if (temp.code == 2300028) { + await new Promise(resolve => setTimeout(resolve, 2000)); // 延迟1秒 + } return await this.sendWriteObjectOut(data, filePath) } } @@ -672,9 +697,9 @@ export default class Judge { this.carztStr = ''; this.testKmItems = {}; // 考试回放配置 - const {isTrajectoryOpen,modelPath,trajectoryPath} = judgeConfig + const {isTrajectoryOpen,trajectoryPath} = judgeConfig this.isTrajectoryOpen = isTrajectoryOpen; - this.modelPath = modelPath; + this.modelPath = 'models'; this.trajectoryPath = trajectoryPath; this.isExam = !this.judgeUI.singlePlay; @@ -702,22 +727,30 @@ export default class Judge { // 获取评判初始化数据 getJudgeInitData = async () => { - const {getModelData,getKm3JudgeInitConfig} = this + const {getModelData,getKm3JudgeInitConfig,bklx} = this const carInfo = globalThis.carInfo; 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 fileUtil = new FileUtil(globalThis.context) + const ipConfigStr = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); + const ipConfig = JSON.parse(ipConfigStr) 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 modelVal= getModelData(`${modelKey}.txt`) + if(modelVal){ + return { + xmdm, xmxh, model: modelVal + } + }else{ + return undefined } - }) + }).filter(item => item !== undefined) } //获取版本号 const sdkver = await examJudgeVersion(); @@ -730,7 +763,7 @@ export default class Judge { kscx: carType, cxcode: '1', name: carName, - carmodel: getModelData(`${examType}/${carType}.txt`), + carmodel: getModelData(`${carType}.txt`), allitems, iteminfo: [], systemparm: systemparmArr, @@ -739,6 +772,8 @@ export default class Judge { itemInfoObj, carlist: judgeUI.carlist, carinfo: carinfoArr, + //板卡类型 + bklx, }; let km3Config = {} @@ -914,7 +949,7 @@ export default class Judge { const {examSubject} = this.judgeUI const xmdm = xmqx.xmdm; const xmmcCode = judgeUI.projectsObj[xmdm].projectCodeCenter; - const voiceCode = getKmProjectCancelVoice(examSubject, xmmcCode); + // const voiceCode = getKmProjectCancelVoice(examSubject, xmmcCode); // avPlayer.playAudio([`voice/${voiceCode}.mp3`],true) this.judgeUI.projectsObj[xmdm].type = '1'; this.testKmItems[xmmcCode].status = '1'; @@ -1171,7 +1206,6 @@ export default class Judge { } } console.info(judgeTag + 'ksxm=>', data.drvexam.ksxm) - const {code} = await this.sendWriteObjectOut(data, filePath); if (code == 2300007) { this.isJudgeDisConnect = true @@ -1199,6 +1233,17 @@ export default class Judge { }) }) } else { + //收到综合评判语音时,显示综合评判弹窗 + if(code[0] == 'zhpp'){ + const param512 = (this.judgeUI.judgeConfigObj['512'] || '').split(','); + this.judgeUI.isDeductedPopShow = false + clearTimeout(this.deductedPopShowTimer) + if(param512[7] != 0){ + this.judgeUI.isDeductedPopShow = true + this.judgeUI.defaultTabIndex = 1 + } + this.isEndTip = true + } avPlayer.playAudio([`voice/${code[0]}.mp3`]) } } @@ -1221,8 +1266,9 @@ export default class Judge { if (!isManual && examSubject == 3 && (param302 == 1 || (singlePlay && param302 == 2)) && totalScore < passingScore) { avPlayer.playAudio([`voice/考试结束.mp3`]) } - //联网模式下手动结束的直接退出 - if (!singlePlay && isManual && !isAllProjectsEnd) { + + //联网模式下:项目没有做完、当前分数大于及格分;手动结束直接退出 + if (!singlePlay && isManual && !isAllProjectsEnd && totalScore >= passingScore) { avPlayer.playAudio(['voice/empty.mp3'], true, () => { this.isUdpEnd = true; closeAllFiles() @@ -1230,32 +1276,18 @@ export default class Judge { }) return } - if (examSubject == 3) { - const param302 = judgeConfigObj['302']; - if (totalScore < passingScore) { - //考试不合格;考试模式,自动退出; - if (param302 == 4 || param302 == 5 || param302 == 7 || param302 == 8) { - } - } else { - //考试合格 - } - } - await handleSEP(306); avPlayer.playAudio(['voice/exam_waiting.mp3'], globalThis.singlePlay, async () => { try { if (!singlePlay) { const bytes = await this.getMessageHeartbeat(true); globalThis.judgeUdp.send(bytes) } - await endExam() } catch (e) { console.info(judgeTag, JSON.stringify(e)) - // setTimeout(() => { - // // avPlayer.avPlayerStop(); - // router.back(); - // }, 3000) } + await endExam() + }); } @@ -1487,7 +1519,9 @@ 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 ? + (examSubject == 2 ? '0000000000000' : '0000000000000') : lsh) || 0, 13) ); //13不足要补0 const ascksyhArr = stringToASC(fillZero(ksyh || 0, 13)) @@ -1640,9 +1674,8 @@ export default class Judge { // 获取模型数据 getModelData = (modelName) => { - const modelPath = this.modelPath const fileModel = this.fileModel; - const modelData = fileModel.getModelContent(modelPath, modelName); + const modelData = fileModel.getModelContent('models', modelName); return modelData } @@ -1720,13 +1753,19 @@ export default class Judge { //开始评判 private async judging(callBack: Function) { const {judgeUI} = this; - const { name, lsh, idCard,kssycs,manualMarkRules} = judgeUI; + const { name, lsh, idCard,kssycs,markRules} = judgeUI; const fileLog = new FileLog(judgeUI.context); const filePath = await fileLog.initFileLogo({ name, lsh, idCard }); + + const ipFileUtil = new FileUtil(globalThis.context) + const ipConfigStr = await ipFileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); + const ipConfig = JSON.parse(ipConfigStr) + this.fileLog = fileLog; this.filePath = filePath; + this.bklx = Number(ipConfig.cardType) const { getJudgeBeginData, @@ -1798,7 +1837,7 @@ export default class Judge { if (!globalThis.singlePlay) { this.videoData = await saveStartRecordVideo(`${name}_${kssycs}`) } - + globalThis.statue = 4 const {examSubject,projectsObj} = this.judgeUI // if(examSubject == 3){ // //不做模拟灯光,需要做上车准备 =>(请上车准备) @@ -1827,7 +1866,8 @@ export default class Judge { handDistance(); } }); - + //页面逻辑处理完成 + this.judgeUI.isInitSuccess = true; // this.checkExamIsEnd() //监听远程结束考试 @@ -1835,18 +1875,33 @@ export default class Judge { this.checkExamIsEnd(true); }) - console.info(judgeTag, JSON.stringify(manualMarkRules)) + console.info(judgeTag, JSON.stringify(markRules)) + //监听远程扣分 globalThis.udpEvent.onKfExam(async (content) => { + //为1时,所有扣分项均可远程扣分;其它,只能扣 MARKSERIAL 大于 99 的扣分项 + const config810 = this.judgeUI.judgeConfigObj['810']; console.info('评判收到远程扣分项目内容' + JSON.stringify(content)) const { kfxh , directives } = content.data; console.info(judgeTag, '评判收到远程扣分项目内容,扣分序号:' + `kfxh=>${kfxh}; directives=>${directives}`) + //根据扣分序号找扣分代码 - const currentKf = manualMarkRules.filter(mark => mark.kfxh == kfxh)[0]; + const currentKf = markRules.filter(mark => ( + mark.kfxh == kfxh && (config810 == 1 || mark.markserial > 99) + ))[0]; + console.info(judgeTag, '扣分项目:' + JSON.stringify(currentKf)) this.setJudgeMark(currentKf.itemno, currentKf.markserial, 2); globalThis.judgeUdp.confirmKf(directives, 1) }) + + //监听远程终止考试 + globalThis.udpEvent.onStopExam(async () => { + const config392 = (this.judgeUI.judgeConfigObj['392'] || '20,81').split(','); + console.info(judgeTag, '开始远程终止考试扣分') + this.setJudgeMark(config392[0]*1, config392[1], 2); + }) + this.checkExamIsEnd(); } diff --git a/entry/src/main/ets/pages/judgeSDK/utils/fileModel.ts b/entry/src/main/ets/pages/judgeSDK/utils/fileModel.ts index 4b43662a..c9131252 100644 --- a/entry/src/main/ets/pages/judgeSDK/utils/fileModel.ts +++ b/entry/src/main/ets/pages/judgeSDK/utils/fileModel.ts @@ -55,10 +55,11 @@ export default class FileModel{ return content; }catch (e){ console.info('surenjun',JSON.stringify(e)) - promptAction.showToast({ - message:`请检查模型路径${folderPath}/${fileName}是否正确!`, - duration:4000 - }) + // promptAction.showToast({ + // message:`请检查模型路径${folderPath}/${fileName}是否正确!`, + // duration:4000 + // }) + return ''; } } diff --git a/entry/src/main/ets/pages/judgeSDK/utils/judgeCommon.ts b/entry/src/main/ets/pages/judgeSDK/utils/judgeCommon.ts index fb3591dc..c40b70f6 100644 --- a/entry/src/main/ets/pages/judgeSDK/utils/judgeCommon.ts +++ b/entry/src/main/ets/pages/judgeSDK/utils/judgeCommon.ts @@ -54,14 +54,23 @@ export function getCarStatusType(carzt){ // 获取档位信号 export function getDwStatusType(dw){ switch (dw){ - case 0:return [0,0,0,0] + case 0: return [0,0,0,0] case 1: return [0,0,0,1] case 2: return [0,0,1,0] case 3: return [0,0,1,1] case 4: return [0,1,0,0] case 5: return [0,1,0,1] + //R档 case 9: return [1,0,0,1] - default :return [0,0,0,0] + //P档位 + case 10: return [1,0,1,0] + //D档 + case 11: return [1,0,1,1] + //S档 + case 12: return [1,1,0,0] + //M档 + case 13: return [1,1,0,1] + default :return [0,0,0,0] } } @@ -98,8 +107,6 @@ export function getKmProjectVoice( const param544Str = judgeConfig['544']?.split(',') || []; const param405Str = judgeConfig['405'] || 0; - console.info('surenjun => param544Str.length',param544Str.length) - const {num,count,road} = lane if(examSubject == 2){ return projectCode @@ -310,12 +317,14 @@ export const plcStrToJson = async (plc:string) =>{ }, gps:{ //办卡类型 定位差分状态 - bklx:p[56], dwzt:p[83], + bklx:Number(p[56]), dwzt:p[83], //@ts-ignore 角度差分状态 jdzt:p[92].split('-')[0]*1, - //gps数据 - //gps时间 经度 纬度 航向角 俯仰角 海拔高 高度差 速度 - sj:time, jd:p[96], wd:p[95], hxj:p[90], fyj:p[91], hbg:p[85], gdc:p[86], sd:p[97], + //一代机、三代机经纬度数据兼容 + //gps时间 经度 纬度 + sj:time, jd:Math.max(Number(p[95]),Number(p[96])), wd:Math.min(Number(p[95]),Number(p[96])), + //航向角 俯仰角 海拔高 高度差 速度 + hxj:p[90], fyj:p[91], hbg:p[85], gdc:p[86], sd:p[97], //龄期 经度因子 纬度因子 定位搜星数 age:p[87], jdyz:p[89], wdyz:p[88], dwsxs:p[84] || 0, //@ts-ignore 角度搜星数 @@ -341,7 +350,7 @@ export const plcStrToWXJson = async (plc:string) =>{ const timeStr = p[93] + '' + p[94]; const gps = { //办卡类型 定位差分状态 - bklx:p[56], dwzt:p[83], + bklx:Number(p[56]), dwzt:p[83], // 经度 纬度 航向角 俯仰角 海拔高 高度差 速度 jd:p[96], wd:p[95], hxj:p[90], fyj:p[91], hbg:p[85], gdc:p[86], sd:p[97], //龄期 经度因子 纬度因子 定位搜星数 diff --git a/entry/src/main/ets/pages/judgeSDK/utils/judgeConfig.ts b/entry/src/main/ets/pages/judgeSDK/utils/judgeConfig.ts index a8e1b4f1..d6ea58e8 100644 --- a/entry/src/main/ets/pages/judgeSDK/utils/judgeConfig.ts +++ b/entry/src/main/ets/pages/judgeSDK/utils/judgeConfig.ts @@ -1,5 +1,6 @@ //考试回放开关 export const judgeConfig = { + version:'2024.08.21.01', //本地目录开关 isTrajectoryOpen: false, //是否开启拍照 @@ -13,13 +14,13 @@ export const judgeConfig = { //轨迹回放是否开启Udp udpOpen:true, // 本地模型地址 - modelPath: 'models/model_enc', + // modelPath: 'models/model_enc', // 济南科目三 - trajectoryPath: 'logs/2024_12_26/2024_12_26_14_12_51_2412505941910_370125200404041910_赵宇/judge_exam_data.txt', + trajectoryPath: 'logs/2025_04_23_09_50_55_2504755332926_320924199111132926_陈静/judge_exam_data.txt', //四合一画面配置 fourInOneScreen:{ //gps位数 - gpsDigit:6 + gpsDigit:7 }, // 杭州科目二 // trajectoryPath: 'logs/2024_07_19/0000000000001_342323199501470011_测试学员1_2024_07_19_06_49_12/judge_exam_data.txt', diff --git a/entry/src/main/resources/rawfile/voice/end_tip.mp3 b/entry/src/main/resources/rawfile/voice/end_tip.mp3 new file mode 100644 index 00000000..3e1aac02 Binary files /dev/null and b/entry/src/main/resources/rawfile/voice/end_tip.mp3 differ diff --git a/entry/src/main/resources/rawfile/voice/zhpp.mp3 b/entry/src/main/resources/rawfile/voice/zhpp.mp3 new file mode 100644 index 00000000..f49a6c82 Binary files /dev/null and b/entry/src/main/resources/rawfile/voice/zhpp.mp3 differ diff --git a/hvigor/hvigor-config.json5 b/hvigor/hvigor-config.json5 index 122677b1..64655e69 100644 --- a/hvigor/hvigor-config.json5 +++ b/hvigor/hvigor-config.json5 @@ -1,6 +1,6 @@ { - "hvigorVersion": "3.0.9", + "hvigorVersion": "3.2.4", "dependencies": { - "@ohos/hvigor-ohos-plugin": "3.0.9" + "@ohos/hvigor-ohos-plugin": "3.2.4" } } \ No newline at end of file diff --git a/oh-package-lock.json5 b/oh-package-lock.json5 index bc40219d..1f023b33 100644 --- a/oh-package-lock.json5 +++ b/oh-package-lock.json5 @@ -1,13 +1,15 @@ { - "lockfileVersion": 1, + "lockfileVersion": 2, "ATTENTION": "THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.", "specifiers": { "@ohos/hypium@1.0.6": "@ohos/hypium@1.0.6" }, "packages": { "@ohos/hypium@1.0.6": { - "resolved": "https://repo.harmonyos.com/ohpm/@ohos/hypium/-/hypium-1.0.6.tgz", - "integrity": "sha512-bb3DWeWhYrFqj9mPFV3yZQpkm36kbcK+YYaeY9g292QKSjOdmhEIQR2ULPvyMsgSR4usOBf5nnYrDmaCCXirgQ==" + "resolved": "https://ohpm.openharmony.cn/ohpm/@ohos/hypium/-/hypium-1.0.6.tgz", + "integrity": "sha512-bb3DWeWhYrFqj9mPFV3yZQpkm36kbcK+YYaeY9g292QKSjOdmhEIQR2ULPvyMsgSR4usOBf5nnYrDmaCCXirgQ==", + "registryType": "ohpm", + "shasum": "3f5fed65372633233264b3447705b0831dfe7ea1" } } } \ No newline at end of file diff --git a/script.bat b/script.bat new file mode 100644 index 00000000..7c57964b --- /dev/null +++ b/script.bat @@ -0,0 +1,27 @@ +@echo off +set TOOLCHAIN_DIR=C:\Users\wangzhongjie\Library\OpenHarmony\Sdk\9\toolchains + +:logs +cd %TOOLCHAIN_DIR% +hdc.exe file recv /mnt/hmdfs/100/account/device_view/local/files/duolun/logs C:\Users\wangzhongjie\Desktop\log +goto :eof + +:hilog +cd %TOOLCHAIN_DIR% +hdc.exe kill +hdc.exe shell "tar -czvf /data/log.tar.gz /data/log/" +hdc.exe file recv /data/log.tar.gz C:\Users\wangzhongjie\Desktop\log +hdc.exe shell "rm -rf /data/log.tar.gz" +goto :eof + +:open +cd %TOOLCHAIN_DIR% +hdc.exe kill +hdc.exe shell hilog -w stop +hdc.exe shell hilog -r +hdc.exe shell hilog -w start -l 100M -m none +hdc.exe shell hilog -Q pidoff +hdc.exe shell hilog -p off +hdc.exe shell hilog -b D +hdc.exe shell hilog -w start -t kmsg -m none +goto :eof \ No newline at end of file diff --git a/subject-two.iml b/subject-two.iml new file mode 100644 index 00000000..68f82594 --- /dev/null +++ b/subject-two.iml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test.bat b/test.bat new file mode 100644 index 00000000..f61d21ff --- /dev/null +++ b/test.bat @@ -0,0 +1,13 @@ +@echo off + +set TOOLCHAIN_PATH=.\win + +cd %TOOLCHAIN_PATH% + +.\hdc.exe kill +.\hdc.exe shell hilog -w stop +.\hdc.exe shell hilog -r + +echo "操作完成" + +pause