diff --git a/entry/src/main/ets/common/service/indexService.ts b/entry/src/main/ets/common/service/indexService.ts deleted file mode 100644 index 6209884d..00000000 --- a/entry/src/main/ets/common/service/indexService.ts +++ /dev/null @@ -1,95 +0,0 @@ -import promptAction from '@ohos.promptAction' -import router from '@ohos.router' -import { deleteAllFileByPiC, takePhoto } from '../../service/videoService' -import { - delSyncTable, - getDataBaseTable, - getMySystemSetTable, - upDataZhongxinginitialization, - upDateTable -} from './initable' -import { GlobalConfig } from '../../config/index' -import testNapi from '@ohos.hiserialsdk' -import fs from '@ohos.file.fs'; - -let num = 0 - - -//配置流水号 - - -let interval - -// 判断摄像头是否遮挡 - -const devPath = "/dev/ttyS3" -let chuankoufd - -function openChuankouFn(callback) { - console.log('SerialOpen in indexservice, path=' + devPath) - - //TODO 自动挡车不读取串口 - testNapi.SerialOpenAsync(devPath, (fd) => { - chuankoufd = fd - // AppStorage.setOrCreate('fd',fd) - // AppStorage.setOrCreate('num',0) - let parity = 0x4e; // 'N' - let ret = testNapi.SerialSetAsync(chuankoufd, 115200, 0, 8, 1, parity, (ret) => { - callback() - }); - }); -} - -function getChuankouFnMsg() { - let timeout = 50000; // 2秒超时 - let databuff = [0x61, 0xAA, 0x0A, 0X15, 0X00]; // send ABCDE - testNapi.SerialSendAsync(chuankoufd, databuff, (ret) => { - testNapi.SerialRecvAsync(chuankoufd, timeout, (revTestInfo) => { - - const message = revTestInfo?.recevedBuf?.toString() - if (message == '') { - // clearInterval(chuankou) - testNapi.SerialClose(chuankoufd); - chuankoufd = null - setTimeout(() => { - getChuankouFn() - }, 2000) - return - } - const msg = message?.split(',') - if (!msg?.length) { - - } else if (msg[0] != '98' || msg[1] != '85' || msg.length < 9) { - - } else if (msg.length < 12) { - - } else { - AppStorage.setOrCreate('chuankoMsg', msg[9]) - } - - setTimeout(() => { - getChuankouFnMsg() - }, 500) - - // hilog.info(0x0000, 'testTag', 'Test NAPI SerialRecvAsync callback in'); - // hilog.info(0x0000, 'testTag', 'Test NAPI SerialRecvAsync recevedLen = %{public}d', revTestInfo.recevedLen); - // hilog.info(0x0000, 'testTag', 'Test NAPI SerialRecvAsync recevedBuf = %{public}s', revTestInfo.recevedBuf.toString()); - }); - - }); - -} - -let chuankou - -export async function getChuankouFn() { - if (chuankoufd) { - return - } - openChuankouFn(getChuankouFnMsg) - // clearInterval(chuankou) - // chuankou=setInterval(()=>{ - // getChuankouFnMsg() - // },1000) - -} \ No newline at end of file diff --git a/entry/src/main/ets/common/service/initable.ets b/entry/src/main/ets/common/service/initable.ets deleted file mode 100644 index 87e18250..00000000 --- a/entry/src/main/ets/common/service/initable.ets +++ /dev/null @@ -1,474 +0,0 @@ -import { initCenterCache, initCenterCacheByKSPT, initEsModel, initialization } from '../../api/index'; -import AccountTable from '../database/tables/AccountTable'; -import MA_MARKRULE from '../constants/MA_MARKRULE'; -import MA_SYSTEMPARM from '../constants/MA_SYSTEMPARM'; -import MA_MAP_COLLECT from '../constants/MA_MAP_COLLECT'; -import MA_MAP_COLLECT_SHAPE from '../constants/MA_MAP_COLLECT_SHAPE'; -import MA_MAP_ITEMCLASS from '../constants/MA_MAP_ITEMCLASS'; -import MA_MAP_POINT from '../constants/MA_MAP_POINT'; -import MA_MAP_POINT_ITEM from '../constants/MA_MAP_POINT_ITEM'; -import MA_MAP_ROAD from '../constants/MA_MAP_ROAD'; -import MA_MAP_ROAD_LANE from '../constants/MA_MAP_ROAD_LANE'; -import MA_MAP_SUBITEM from '../constants/MA_MAP_SUBITEM'; -import MA_SYSSET from '../constants/MA_SYSSET'; -import ES_CARINFO from '../constants/ES_CARINFO'; -import ES_EXAMPOINTDETAIL from '../constants/ES_EXAMPOINTDETAIL'; -import MA_MARKRULESET from '../constants/MA_MARKRULESET'; -import MA_CDSBINFO from '../constants/MA_CDSBINFO'; -import MA_ITEMINFO from '../constants/MA_ITEMINFO'; -import MA_T_CARPARMSET from '../constants/MA_T_CARPARMSET'; -import ES_CAR_VIDEO_PARAMETER from '../constants/ES_CAR_VIDEO_PARAMETER'; -import IpConfigTable from '../constants/IpConfigTable'; -import CommonConstants from '../constants/CommonConstants'; -import DeviceInfoTable from '../constants/DeviceInfoTable'; -import USER from '../constants/USER'; -import USERLIST from '../constants/USERLIST'; -import util from '@ohos.util'; -import FileModel from '../../pages/judgeSDK/utils/fileModel'; - -import { GlobalConfig } from '../../config/index'; -import prompt from '@ohos.promptAction'; -import DB, { ColumnType } from '../database/DbSql'; -import FileUtils from '../../utils/FileUtils'; -import { TimeSynchronizationRspBody } from '../../model'; - -//读表 -//参数平台 -const map = { - 'MA_MARKRULE': MA_MARKRULE, - 'MA_SYSTEMPARM': MA_SYSTEMPARM, - 'MA_MAP_COLLECT': MA_MAP_COLLECT, - 'MA_MAP_COLLECT_SHAPE': MA_MAP_COLLECT_SHAPE, - 'MA_MAP_ITEMCLASS': MA_MAP_ITEMCLASS, - 'MA_MAP_POINT': MA_MAP_POINT, - 'MA_MAP_POINT_ITEM': MA_MAP_POINT_ITEM, - 'MA_MAP_ROAD': MA_MAP_ROAD, - 'MA_MAP_ROAD_LANE': MA_MAP_ROAD_LANE, - 'MAP_SUBITEM': MA_MAP_SUBITEM, - 'MA_MAP_SUBITEM': MA_MAP_SUBITEM, - 'MA_SYSSET': MA_SYSSET, - 'ES_CARINFO': ES_CARINFO, - 'ES_EXAMPOINTDETAIL': ES_EXAMPOINTDETAIL, - 'MA_MARKRULESET': MA_MARKRULESET, - 'MA_CDSBINFO': MA_CDSBINFO, - 'MA_ITEMINFO': MA_ITEMINFO, - 'MA_T_CARPARMSET': MA_T_CARPARMSET, - 'ES_CAR_VIDEO_PARAMETER': ES_CAR_VIDEO_PARAMETER, - 'USER': USER, - 'USERLIST': USERLIST, - 'IpConfigTable': IpConfigTable, - 'DeviceInfoTable': DeviceInfoTable, - 'CommonConstants': CommonConstants -} -const centerToMap = { - 'ItemInfo': MA_ITEMINFO, - 'MarkRule': MA_MARKRULE, - 'SystemParm': MA_SYSTEMPARM, - 'mapCollectList': MA_MAP_COLLECT, - 'mapCollectshapeList': MA_MAP_COLLECT_SHAPE, - 'Map_Collect': MA_MAP_COLLECT, - 'Map_Collect_Shape': MA_MAP_COLLECT_SHAPE, - 'Map_ItemClass': MA_MAP_ITEMCLASS, - 'Map_Point': MA_MAP_POINT, - 'Map_Point_Item': MA_MAP_POINT_ITEM, - 'Map_Road': MA_MAP_ROAD, - 'Map_Road_Lane': MA_MAP_ROAD_LANE, - 'Map_SubItem': MA_MAP_SUBITEM, - 'Sysset': MA_SYSSET, - 'CarInfo': ES_CARINFO, - 'MarkRuleSet': MA_MARKRULE, - 'Cdsbinfo': MA_CDSBINFO, - 'T_CarParmSet': MA_T_CARPARMSET, -} - -// 建表操作 -export async function initTable() { - console.log("sql inittable") - for (let key in map) { - await DB.executeSql(map[key].ACCOUNT_TABLE.sqlCreate) - } -} - -export function sqlInsertCommonFn(tableName, resultArr, delFlag = true) { - return new Promise((resolve, reject) => { - DB.clearTable(tableName).then((res) => { - let INSERT_SQL = "INSERT INTO " + tableName - + " (" + map[tableName].ACCOUNT_TABLE.columns.toString() + ") VALUES " - - resultArr.map((data, i) => { - data.id = !delFlag ? `${i + resultArr.length}` : `${i}` - let str = '(' - map[tableName].ACCOUNT_TABLE.columns.map((res, index) => { - if (map[tableName].ACCOUNT_TABLE.columns.length - 1 == index) { - str += data[res] ? `'${data[res]}'` : 'NULL' - } else { - str += (data[res] ? `'${data[res]}'` : 'NULL') + ',' - } - }) - if (i == resultArr.length - 1) { - str += ')' - } else { - str += '),' - } - INSERT_SQL += str - }) - console.log("sql insert sqlCode", INSERT_SQL) - DB.executeSql(INSERT_SQL).then(() => { - console.log('sql insert,', res, 'tableName', tableName) - resolve(true) - }).catch((err) => { - console.log('sql insert err,', JSON.stringify(err), 'tableName', tableName) - reject(err) - }) - }) - }) -} - -//参数平台 -export async function getDataBaseTable(params, reqParam) { - return new Promise(async (resolve, reject) => { - const date = new Date() - if (!reqParam?.paraKdid) { - prompt.showToast({ - message: 'paraKdid获取失败', - duration: 3000 - }); - return - } - const str = { - "head": { "time": dateFormat(date) }, - "body": - { - "tableName": params.tableName, // 表名 - "paraKdid": reqParam.paraKdid, //参数平台kdid - "examinationRoomId": reqParam.examinationRoomId, //考试平台kdid - "typeRsp": "0" // 赋默认值0,无需改变 - } - } - let res: any = await initCenterCache(str, reqParam.centerHost) - if (res.body[params.tableName].length == 0) { - resolve(); - return - } - if (params.tableName == 'MA_SYSSET') { - res.body[params.tableName] = res.body[params.tableName].filter(res => { - return res['v_no'] < 300 || res['v_no'] > 700 - }) - } - sqlInsertCommonFn(params.tableName, res.body[params.tableName], reqParam.context).then((val) => { - // resolve(val) - resolve() - }) - }) -} - -//依据数组和表名更新sql表 -export async function upDateTableByArray(tableName, arr) { - return new Promise(async (reslove, reject) => { - const data = await sqlInsertCommonFn(tableName, arr) - reslove(data) - }) -} - -//更新双中心表 -export async function upDateTable(params, reqParam) { - return new Promise((resolve, reject) => { - const date = new Date() - let paraKdid = reqParam?.paraKdid || '' - let examinationRoomId = reqParam?.kdid || '' - if (!paraKdid || !examinationRoomId) { - resolve(false) - return - } - - const str = { - "head": { "time": dateFormat(date) }, - "body": - { - "tableName": params.tableName, // 表名 - "paraKdid": reqParam.paraKdid, //参数平台kdid - "examinationRoomId": reqParam.kdid, //考试平台kdid - "typeRsp": "0" // 赋默认值0,无需改变 - } - } - const url = reqParam.centerHost - - initCenterCache(str, url).then(async (res: ESObject) => { - if (!res || res == undefined || res == '') { - resolve(false) - return - } - try { - const result = await sqlInsertCommonFn(params.tableName, res.body[params.tableName], reqParam.context) - resolve(result) - } catch (error) { - console.log(error) - } - }) - }); -} - -//考试平台 -export async function getMySystemSetTable(params, reqParam) { - return new Promise((resolve, reject) => { - const date = new Date() - if (!reqParam.paraKdid) { - prompt.showToast({ - message: 'paraKdid获取失败', - duration: 3000 - }); - return - } - const str = { - "head": { "time": dateFormat(date) }, - "body": - { - "tableName": params.tableName, // 表名 - "paraKdid": reqParam?.paraKdid, //参数平台kdid - "examinationRoomId": reqParam?.kdid, //考试平台kdid - "typeRsp": "0" // 赋默认值0,无需改变 - } - } - initCenterCacheByKSPT(str, reqParam.url).then((res: ESObject) => { - if (res.body[params.tableName].length == 0) { - resolve(); - return - } - if (params.tableName == 'MA_SYSSET') { - res.body[params.tableName] = res.body[params.tableName].filter(res => { - return res['v_no'] >= 300 && res['v_no'] <= 700 - }) - } - sqlInsertCommonFn(params.tableName, res.body[params.tableName], false).then((result) => { - // resolve(result) - resolve() - }) - }) - - - }) - -} - -//依据表名同步获取数据 -export async function getSyncData(tableName, context?) { - return new Promise((resolve, reject) => { - const column = map[tableName].ACCOUNT_TABLE.columns.map(res => { - return { - name: res, - columnName: res, - type: ColumnType.STRING - } - }) - DB.queryListBySql(`select * from ${tableName}`, column).then(res => { - console.log("sql MA_SYSSET", JSON.stringify(res)) - resolve(res) - }).catch(err => { - console.log("sql err MA_SYSSET", JSON.stringify(err)) - reject(err) - }) - }) -} - -export async function delSyncTable(tableName, context?) { - return new Promise((resolve, reject) => { - const accountTable = new AccountTable(() => { - const SQL = `DELETE FROM ${tableName};` - console.log("sql message 删除操作,表", tableName) - accountTable.sqlOperate(SQL, tableName, (val) => { - console.log('teststet3', '删除成功') - resolve(val) - }) - }, map[tableName], context); - - // accountTable.deleteTableData((ret) => { - // console.log('删除成功') - // resolve(true) - // }, tableName, context) - - }) -} - -//获取车模、场地模型 -export async function getEsCarModel(context) { - const date = new Date() - const timeInfo = AppStorage.get('timeInfo') - if (!timeInfo?.paraKdid) { - prompt.showToast({ - message: 'paraKdid获取失败', - duration: 3000 - }); - return - } - const carStr = { - "head": { "time": dateFormat(date) }, - "body": - { - "rtkType": "1", //1:车模 2:场地模型 - "rspType": "0", //返回类型 - "paraKdid": timeInfo.paraKdid, //参数平台kdid - "examinationRoomId": timeInfo.kdid, //考试平台kdid - // "carMac":"MAC-HCPAD-210", - "carMac": AppStorage.get('deviceNo') - } - } - const venueStr = { - "head": { "time": dateFormat(date) }, - "body": - { - "rtkType": "2", //1:车模 2:场地模型 - "rspType": "0", //返回类型 - "paraKdid": timeInfo.paraKdid, //参数平台kdid - "examinationRoomId": timeInfo.kdid, //考试平台kdid - // "carMac":"MAC-HCPAD-210", - "carMac": AppStorage.get('deviceNo') - } - } - - - let carRes: any = await initEsModel(carStr); - let venueRes: any = await initEsModel(venueStr); - - const carModel = carRes.body.ES_MODEL[0][1]; - const venueModel = venueRes.body.ES_MODEL[0][2]; - - let tmpBase64Array = carModel.split("\r\n") - let newBase64Str: string = ''; - for (let i = 0; i < tmpBase64Array.length; ++i) { - newBase64Str += tmpBase64Array[i]; - } - const base64 = new util.Base64(); - let result = base64.decodeSync(newBase64Str); - const fileModel = new FileModel(context); - await fileModel.initFolder() - await fileModel.storingFiles(result.buffer) -} - -export async function upDataZhongxinginitialization(param) { - return new Promise(async (resolve, reject) => { - console.log('teststet00', JSON.stringify(param)) - let flag = true - if (param.singlePlay) { - console.log('teststet0', JSON.stringify(param)) - const fileUtil = new FileUtils(param.context) - const tableList = - ['MA_SYSSET', 'MA_SYSTEMPARM', 'MA_MARKRULE', 'MA_MARKRULESET', 'ES_CARINFO', 'MA_MAP_ROAD', 'MA_MAP_ROAD_LANE', - 'MAP_SUBITEM', 'MA_T_CARPARMSET', 'MA_MAP_ITEMCLASS', 'MA_MAP_POINT', 'MA_MAP_POINT_ITEM']; - for (let i = 0; i <= tableList.length - 1; i++) { - const data = - await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + `/config/tableList/${tableList[i]}.txt`); - const result = await sqlInsertCommonFn(tableList[i], JSON.parse(data) || [], param.context) - - result ? (flag = true) : (flag = false) - } - console.log('teststet1', JSON.stringify(param)) - - if (!flag) { - prompt.showToast({ - message: '本地文件初始化数据库失败', - duration: 3000 - }); - } - console.log("init table1") - resolve(flag) - return - } - if (!param.carId) { - console.log("init table2") - resolve(false) - return - } - try { - const str = { - "carId": param.carId, // 表名 - "examinationRoomId": param.examinationRoomId, //考试平台kdid - videoVersion: '1.0', - judgeVersion: param.judgeVersion, - shellVersion: param.shellVersion, - host: param.host - } - console.log('daihai2', JSON.stringify(str)) - - initialization(str).then(async (res: ESObject) => { - console.log('daihai3', JSON.stringify(res)) - if (!res || res.initializationRsp.head.resultCode == 1) { - console.log('daihai34', JSON.stringify(res)) - console.log("init table3") - resolve(false) - return - } - let flag - console.log('resposestart') - - for (let key in res.initializationRsp.body) { - if (!centerToMap[key]) { - continue - } - const data = await setSyncCenterSqlData(key, res, param) - if (!data) { - console.log("init table4") - resolve(false) - } - } - resolve(true) - }).catch((Error) => { - console.log("init table5", JSON.stringify(Error)) - resolve(false) - }) - } catch (error) { - console.log("init table6", JSON.stringify(error)) - resolve(false) - } - }) -} - -function setSyncCenterSqlData(key, res, param) { - return new Promise(async (resolve, reject) => { - const mapName = { - 'ItemInfo': 'MA_ITEMINFO', - 'MarkRule': 'MA_MARKRULE', - 'SystemParm': 'MA_SYSTEMPARM', - 'Map_Collect': 'MA_MAP_COLLECT', - 'Map_Collect_Shape': 'MA_MAP_COLLECT_SHAPE', - 'Map_ItemClass': 'MA_MAP_ITEMCLASS', - 'Map_Point': 'MA_MAP_POINT', - 'Map_Point_Item': 'MA_MAP_POINT_ITEM', - 'Map_Road': 'MA_MAP_ROAD', - 'Map_Road_Lane': 'MA_MAP_ROAD_LANE', - 'Map_SubItem': 'MAP_SUBITEM', - 'Sysset': 'MA_SYSSET', - 'CarInfo': 'ES_CARINFO', - // 'ES_EXAMPOINTDETAIL':ES_EXAMPOINTDETAIL, - 'MarkRuleSet': 'MA_MARKRULESET', - 'Cdsbinfo': 'MA_CDSBINFO', - 'T_CarParmSet': 'MA_T_CARPARMSET', - } - let arrList - if (res.initializationRsp.body[key].record instanceof Array) { - arrList = res.initializationRsp.body[key].record - } else { - arrList = [res.initializationRsp.body[key].record] - } - const fileUtil = new FileUtil(param.context) - const folderPath = await fileUtil.initFolder(`/config/tableList`); - fileUtil.addFile(`${folderPath}/${mapName[key]}.txt`, JSON.stringify(arrList)) - - console.log('mapName[key]', mapName[key], key) - sqlInsertCommonFn(mapName[key], arrList, param.context).then((result) => { - console.log(key, '表建立成功') - // writeLog('PLC',{ - // time:dateFormat(new Date()), - // PLC:`${key} 表建立成功`, - // }) - if (result) { - resolve(true) - } else { - resolve(false) - } - }).catch((msg) => { - reject(false) - console.log(key, '表建立失败') - }) - }) - -} diff --git a/entry/src/main/ets/common/utils/GlobalTcp.ts b/entry/src/main/ets/common/utils/GlobalTcp.ts deleted file mode 100644 index d71c8287..00000000 --- a/entry/src/main/ets/common/utils/GlobalTcp.ts +++ /dev/null @@ -1,92 +0,0 @@ -import TcpClient from './TcpClient'; -import { GlobalConfig } from '../../config/index'; - -let intervalSendmsg - -export async function getTCP(flag = false) { - globalThis.getCloseTcp = true - const context = AppStorage.get('context') - const fileUtil = new FileUtil(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) - 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) - // globalThis.TcpClient = tcpClient - setTimeout(async () => { - const tcpClient: TcpClient = - new TcpClient(result.tcplocalIp, result.tcplocalIpPort, result.tcpOppositeIp, result.tcpOppositePort) - globalThis.TcpClient = tcpClient - await globalThis.TcpClient.bindTcp() - // await globalThis.TcpClient.rebindTcp(result.tcplocalIp, result.tcplocalIpPort, result.tcpOppositeIp, result.tcpOppositePort) - await globalThis.TcpClient.connectTcp() - console.log('ttttttt0') - // await globalThis.TcpClient.sendMsg(globalThis.carInfo.carNo) //1002 - console.log('ttttttt00') - - clearInterval(intervalSendmsg) - intervalSendmsg = setInterval(() => { - if (!globalThis.getCloseTcp) { - globalThis.TcpClient.sendMsg(AppStorage.get('carInfo').carNo) //1002 - } - }, 1000 / 3) - globalThis.TcpClient.onError((val) => { - setTimeout(() => { - getTCP() - }, 1000) - }) - 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) - } - }, 1000) - - }) - }, 2000) - }) - - } else { - const tcpClient: TcpClient = - new TcpClient(result.tcplocalIp, result.tcplocalIpPort, result.tcpOppositeIp, result.tcpOppositePort) - globalThis.TcpClient = tcpClient - await globalThis.TcpClient.bindTcp() - await globalThis.TcpClient.connectTcp() - console.log('ttttttt1') - await globalThis.TcpClient.sendMsg(globalThis.carInfo.carNo) //1002 - console.log('ttttttt12') - - clearInterval(intervalSendmsg) - intervalSendmsg = setInterval(() => { - // console.log('getCloseTcp',globalThis.getCloseTcp) - if (!globalThis.getCloseTcp) { - globalThis.TcpClient.sendMsg(globalThis.carInfo.carNo) //1002 - } - }, 1000 / 3) - globalThis.TcpClient.onError((val) => { - setTimeout(() => { - getTCP() - }, 1000) - }) - await globalThis.TcpClient.onMessage((val) => { - setTimeout(() => { - if (val && globalThis.udpClient?.sendMsg) { - globalThis.udpClient?.sendMsg(val) - } - }, 1000) - - }) - } - } - -} - - -// globalThis.udpClient.bindUdp() diff --git a/entry/src/main/ets/common/utils/GlobalUdp.ts b/entry/src/main/ets/common/utils/GlobalUdp.ts deleted file mode 100644 index dca009b4..00000000 --- a/entry/src/main/ets/common/utils/GlobalUdp.ts +++ /dev/null @@ -1,258 +0,0 @@ -//import UdpClient from './UdpClient'; -import UdpClientByCenter from './UdpClientByCenter'; -import { getChuankouFn } from '../../common/service/indexService'; - - -export async function sendMsg(val) { - // globalThis.udpClient1&&globalThis.udpClient1.sendMsg(val) -} - -// obj -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) - if (data === '' || data === undefined) { - console.log(` getUDP has no IPConfigTable `); - globalThis.udpClient = {} - - reslove('') - } else { - 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.sendMsg('111', null) - AppStorage.setOrCreate('host', `http://${result.centerIp}:${result.centerPort}`) - 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 - } - }) - reslove(`http://${result.centerIp}:${result.centerPort}`) - - // globalThis.udpClient.onError_resend(globalThis.udpClient.onMessage_1?globalThis.udpClient.onMessage_1:()=>{}) - }, 1000) - }) - - } 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) - udpClient.bindUdp() - udpClient.sendMsg('111') - AppStorage.setOrCreate('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 - } - }) - getChuankouFn() - reslove(`http://${result.centerIp}:${result.centerPort}`) - - } - - } - }) - -} - -// 中心 -export async function getUDP2(context, errorFlag?) { - const fileUtil = new FileUtil(context) - const carInfo = AppStorage.get('carInfo') - 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) - 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', carInfo?.udpAddress, - 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 { - // 未绑定 - console.log(` getUDP2 has no udclent and bind `); - const udpClient2: UdpClientByCenter = - new UdpClientByCenter(result.udplocalIp, '8800', carInfo?.udpAddress, - carInfo?.messagePort) - console.info('surenjun udp2=> ', 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 - } - }) - if (!errorFlag) { - await udpClient2.onMessage_2((val) => { - if (val.id == '32') { - AppStorage.setOrCreate('signNum', val.body[1]) - 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事件') - globalThis.udpEvent.sendBeginExam(val.body[1]) - } - if (val.body[0] == 12) { - console.info('surenjun', 'GlobalUdp收到endExam事件') - globalThis.udpEvent.sendEndExam(val.body[1]) - } - } - if (val.id == '36') { - //获取远程扣分内容 - console.info('surenjun', '考车收到远程扣分项目内容,扣分代码:' + val.body[0]) - globalThis.udpEvent.sendKfContent(val.body[0]) - } else if (val.id == '46') { - let tmpList = [] - const str = AppStorage.get('lsh') - for (let i = 0; i < str.length; i++) { - tmpList.push(this.string2Bytes(str.charCodeAt(i), 1 * 8)[0]) - } - const param = { - id: 47, - list: tmpList, - carNo: carInfo.carNo, - placeId: carInfo.examinationRoomId - } - globalThis.udpClient2.send(param) - } - }) - } - globalThis.udpClient2 = udpClient2 - - } - } - -} - -// 灯光 -export async function setTopLineUdp() { - const context = AppStorage.get('context') - const fileUtil = new FileUtil(context) - const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); - const config = JSON.parse(data) - - // const config = await getSyncData('IpConfigTable'); - if (config && config.udplocalIp) { - const { udplocalIp, udpOppositeIp, udpOppositeIpPort } = config; - const udpClient: UdpClientByCenter = new UdpClientByCenter(udplocalIp, '55509', udpOppositeIp, udpOppositeIpPort) - udpClient.bindUdp() - - return { - send(bytes) { - udpClient.sendHeadMsg(bytes) - } - } - } -} - -// -let judgeUdpTimer - -// 评判 -export async function setJudgeUdp() { - const context = AppStorage.get('context') - const fileUtil = new FileUtil(context) - const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt'); - const config = JSON.parse(data) - const carInfo = AppStorage.get('carInfo') - // - // const config = await getSyncData('IpConfigTable'); - let udpIndex = 0; - let currentUdpIndex = 0; - clearInterval(judgeUdpTimer) - judgeUdpTimer = setInterval(() => { - udpIndex += 1; - }, 1000); - - if (config && config.udplocalIp) { - const { udplocalIp } = config; - const udpClientbyCenter: UdpClientByCenter = new UdpClientByCenter( - udplocalIp, '8080', - carInfo?.udpAddress, - carInfo?.hintPort - ) - console.info('surenjun hintPort=> ', carInfo?.hintPort) - - await udpClientbyCenter.onError_Callback(() => { - }) - await udpClientbyCenter.bindUdp() - await udpClientbyCenter.onMessage_2((val) => { - }) - - //远程监听开始考试、结束考试、扣分指令 - - // globalThis.judgeUdpClient = udpClientbyCenter; - return { - send(bytes) { - if (udpIndex > currentUdpIndex) { - udpClientbyCenter.sendMsgExt({ - id: 45, - list: bytes, - carNo: carInfo.carNo, - placeId: carInfo.examinationRoomId - }) - currentUdpIndex = udpIndex - } - }, - - //申请远程扣分查询 - askKf(directives) { - globalThis.udpClient2.sendMsgExt({ - id: 35, - list: [directives], - carNo: carInfo.carNo, - placeId: carInfo.examinationRoomId, - }) - console.info('surenjun', `考车查询扣分项目内容,请求指令为:${directives}`) - }, - - //确定远程扣分 - confirmKf(directives, code) { - globalThis.udpClient2.sendMsgExt({ - id: 37, - list: Array2Byte([string2Bytes(directives, 8), string2Bytes(code, 8)]), - carNo: carInfo.carNo, - placeId: carInfo.examinationRoomId - }) - console.info('surenjun', `考车发送确定扣分指令,指令为:${directives}`) - }, - } - } - -} - -// globalThis.udpClient.bindUdp() diff --git a/entry/src/main/ets/common/utils/TcpClient.ts b/entry/src/main/ets/common/utils/TcpClient.ts deleted file mode 100644 index 14fd97ed..00000000 --- a/entry/src/main/ets/common/utils/TcpClient.ts +++ /dev/null @@ -1,244 +0,0 @@ -import socket from '@ohos.net.socket'; -import hilog from '@ohos.hilog'; -import { getTCP } from './GlobalTcp'; -import prompt from '@ohos.prompt'; - -import App from '@system.app'; - -const TAG = 'socketTag[TcpDemo.TcpClient]' - -export default class TcpClient { - private localIp: string = '' - private localIpPort: string = '' - private oppositeIp: string = '' - private oppositeIpPort: string = '' - private num: number = 0 - //重连次数 - private tcpSendNum: number = 0 - //重连次数 - private folderPath - - private tcp: any = null - - constructor(tcplocalIp: string, tcplocalIpPort: string, tcpOppositeIp: string, tcpOppositePort: string) { - this.localIp = tcplocalIp - this.oppositeIp = tcpOppositeIp - this.localIpPort = tcplocalIpPort - this.oppositeIpPort = tcpOppositePort - console.log(TAG, 'new Tcp', this.localIp, this.localIpPort, this.oppositeIp, this.oppositeIpPort) - this.tcp = socket.constructTCPSocketInstance(); - this.initPath() - } - - onError(callback?) { - this.tcp.on('error', err => { - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} tcpOnerror ${JSON.stringify(err)}`, - // }) - - AppStorage.setOrCreate('getCloseTcp', true) - - - console.log(TAG, 'getCloseTtcpOnerror', JSON.stringify(err)) - setTimeout(async () => { - getTCP() - }, 2000) - // this.closeUdp(()=>{ - // this.bindUdp() - // }) - }); - } - - - bindTcp() { - this.writeLog({ - time: dateFormat(new Date()), - message: `${TAG} tcpbind localIp${this.localIp} ${this.localIpPort}`, - }) - return new Promise((resolve, reject) => { - let promise = this.tcp.bind({ - address: this.localIp, port: parseInt(this.localIpPort), family: 1 - }, err => { - if (err) { - this.writeLog({ - time: dateFormat(new Date()), - message: `${TAG} tcpbind error ${JSON.stringify(err)}`, - }) - setTimeout(async () => { - getTCP() - }, 2000) - console.log('getCloseTBinderror'); - hilog.info(0x0000, 'testTag', "tcpBinderror:" + JSON.stringify(err)); - resolve(true) - return - } - - // console.log('testTag tcp bind success'); - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} testTag tcp bind success`, - // }) - resolve(false) - }) - }) - - } - - connectTcp() { - this.writeLog({ - time: dateFormat(new Date()), - message: `${TAG} tcpConnect oppositeIp ${this.oppositeIp} ${this.oppositeIpPort}`, - }) - return new Promise((resolve, reject) => { - let promise = this.tcp.connect({ - address: { - address: this.oppositeIp, port: parseInt(this.oppositeIpPort), family: 1 - }, timeout: 6000 - }); - promise.then(() => { - this.tcp.setExtraOptions({ - keepAlive: true, - }, err => { - if (err) { - this.writeLog({ - time: dateFormat(new Date()), - message: `${TAG} TCPconnect error ${JSON.stringify(err)}`, - }) - setTimeout(() => { - getTCP() - resolve(false) - }, 9000) - return; - } - }); - AppStorage.setOrCreate('getCloseTcp', false) - resolve(true) - }).catch(err => { - console.log('socketTag', 'error') - this.writeLog({ - time: dateFormat(new Date()), - message: `${TAG} TCPconnect error2 ${JSON.stringify(err)}`, - }) - - setTimeout(() => { - getTCP() - resolve(false) - }, 9000) - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} tcp connect error`, - // }) - }); - }) - } - - sendMsg(msg: string) { - return new Promise((reslove, reject) => { - let promise = this.tcp.send({ - data: msg - }); - promise.then(() => { - reslove(true) - }).catch(err => { - this.tcpSendNum++ - if (!AppStorage.get('getCloseTcp') && this.tcpSendNum > 10) { - setTimeout(async () => { - getTCP(true) - }, 3000) - this.tcpSendNum = 0 - return - } - AppStorage.set('getCloseTcp', true) - console.log(`${TAG} TCPsend error ${JSON.stringify(err)}`) - // this.writeLog({ - // time:dateFormat(new Date()), - // message: `${TAG} TCPsend error ${JSON.stringify(err)}`, - // }) - reslove(false) - }); - }) - } - - onMessage(callback?) { - this.tcp.on('message', value => { - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} Tcponmessage`, - // }) - AppStorage.setOrCreate('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) - } else { - callback && callback('') - } - clearInterval(globalThis.intervaltcp) - globalThis.intervaltcp = setInterval(() => { - //程序断开 - if (globalThis.tcpUdpError) { - console.log(TAG, 'tcp信号丢失') - // getTCP() - prompt.showToast({ - message: 'tcp信号丢失', - duration: 2000 - }); - } - this.writeLog({ - time: dateFormat(new Date()), - message: `${TAG} tcp信号丢失`, - }) - AppStorage.setOrCreate('tcpUdpError', true) - }, 3000) - // callback(value.message) - }); - } - - async writeLog(param) { - // const fileUtil = new FileUtil(globalThis.context) - // fileUtil.editFile(`${this.folderPath}/plcLog.txt`, JSON.stringify(param)+`\n`) - } - - async initPath() { - return - const fileUtil = new FileUtil(globalThis.context) - const date = dateFormat(new Date).split(' ')[0] - this.folderPath = await fileUtil.initFolder(`/PLC/${date}`); - } - - offTcp(callback) { - console.log(TAG, 'tcpofff') - this.tcp.off('testTagofmessg', callback); - } - - closeTcp(callback) { - return new Promise((reslove, reject) => { - console.log(TAG, 'tcpClose') - let promise = this.tcp.close(); - promise.then(() => { - AppStorage.setOrCreate('getCloseTcp', true) - this.writeLog({ - time: dateFormat(new Date()), - message: `${TAG} tcp closeSuccess`, - }) - callback() - reslove(true) - }).catch(err => { - setTimeout(async () => { - getTCP(true) - }, 9000) - this.writeLog({ - time: dateFormat(new Date()), - message: `${TAG} tcpclose error ${JSON.stringify(err)}`, - }) - - reslove(false) - }); - }) - } -} \ No newline at end of file diff --git a/entry/src/main/ets/common/utils/UdpClientByCenter.ts b/entry/src/main/ets/common/utils/UdpClientByCenter.ts deleted file mode 100644 index a0ec70c8..00000000 --- a/entry/src/main/ets/common/utils/UdpClientByCenter.ts +++ /dev/null @@ -1,413 +0,0 @@ -/* - * Copyright (c) 2022 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// @ts-ignore -import socket, { UDPSocket } from '@ohos.net.socket'; - -const TAG = '[UdpDemo.UdpClient]' -import hilog from '@ohos.hilog'; -import prompt from '@ohos.prompt' -import promptAction from '@ohos.promptAction'; -import { getUDP } from './GlobalUdp'; -import { getSyncData } from '../service/initable'; -import App from '@system.app'; - - -export default class UdpClientByCenter { - public currentValue: string = '' - private localIp: string = '' - private localIpPort: string = '' - private oppositeIp: string = '' - private oppositeIpPort: string = '' - private udpMsg: any = '' - private chafenFlag: number = 0 - private num: number = 0 - private fileUtil: FileUtil - private udp: UDPSocket = null - private sendId: any = 0 - private lsh: string = null - private folderPath - private stashFn: StashFunction - private errorStep: number = 0 - private messageTimer: number = -1 - private headLenth: number = 9 - //消息头长度 - private isWorking: Boolean = false - private plcUdpError = false; - private initParam - - constructor(udplocalIp: string, udplocalIpPort: string, udpOppositeIp: string, udpOppositeIpPort: string) { - this.localIp = udplocalIp - this.oppositeIp = udpOppositeIp - this.localIpPort = udplocalIpPort - this.oppositeIpPort = udpOppositeIpPort - this.stashFn = () => { - } - this.udp = socket.constructUDPSocketInstance(); - this.initPath() - } - - rebindUdp(localIp: string, localIpPort: string, oppositeIp: string, oppositeIpPort: string) { - this.localIp = localIp - this.oppositeIp = oppositeIp - this.localIpPort = localIpPort - this.oppositeIpPort = oppositeIpPort - - let promise = this.udp.bind({ - // address: '192.168.7.170', port: 20122, family: 1 - address: this.localIp, port: parseInt(this.localIpPort), family: 1 - }); - - promise.then(() => { - this.isWorking = true - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} getUDPudp rebind success`, - // }) - }).catch(err => { - this.isWorking = false - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} getUDPudp rebind failed:${JSON.stringify(err)}`, - // }) - console.log(`${TAG} getUDPudp rebind failed:${JSON.stringify(err)}`); - }); - } - - bindUdp() { - let promise = this.udp.bind({ - address: this.localIp, port: parseInt(this.localIpPort), family: 1 - }); - promise.then(() => { - this.isWorking = true - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} getUDPudp bind success`, - // }) - }).catch(err => { - this.isWorking = false - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG} getUDPudp bind error${JSON.stringify(err)},localIp:${this.localIpPort},port:${this.localIpPort}`, - // }) - }); - } - - //异或运算 - setMessageExclusive(tmpList) { - let result = tmpList[0]; - for (let i = 1; i < tmpList.length; i++) { - result = result ^ tmpList[i] - } - return [result]; - } - - Array2Byte(array) { - var buf = new ArrayBuffer(array.length); - var view = new Uint8Array(buf); - for (var i = 0; i != array.length; ++i) { - view[i] = array[i] & 0xFF; - } - return view; - } - - // {id: 31,list:[0,1,'0000000000000'],carNo:489,placeId:62} - setWholeMsg(params) { - let head = this.setMsgHead(params); - let headJudge = this.setMessageExclusive(head); - let body = this.setMsgBody(params); - let bodyJudge = this.setMessageExclusive(body); - let end = [13, 10]; - const arr = [...head, ...headJudge, ...body, ...bodyJudge, ...end] - return this.Array2Byte(arr).buffer - - } - - //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)}${AppStorage.get('lshNo')}`, 4 * 8); - let c = string2Bytes(list.length, 2 * 8); - return [...a, ...b, ...c]; - } - - setMsgBody({ id, list }) { - let tmpList = [] - tmpList = list - - return tmpList; - - } - - sendHeadMsg(msgData) { - console.log('getUDPsendHeadMsg enter') - this.sendMsg(msgData, null) - console.log('getUDPsendHeadMsg exit') - } - - 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) { - sendCallback() - } - return; - } - let promise = this.udp.send({ - data: msg, - address: { - address: this.oppositeIp, - port: parseInt(this.oppositeIpPort), - } - }); - promise.then(() => { - if (sendCallback) { - sendCallback() - } - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:`${TAG}getUDPudpCLient udp send success: oppositeIp:${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort:${this.localIpPort}`, - // }) - }).catch(err => { - // this.writeLog({ - // time:dateFormat(new Date()), - // 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 - }) - }); - } - - sendMsgExt(param, context?) { - if (context) { - this.context = context - } - this.sendId = param.id - const msgData = this.setWholeMsg(param) - this.sendMsg(msgData, param.sendCallback) - } - - onError_Callback(callback?) { - this.udp.on('error', async err => { - this.isWorking = false; - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:'getUDPUdpClientByCenter onError err:' + JSON.stringify(err)+this.oppositeIpPort, - // }) - callback && callback() - }); - } - - onError_resend(callback?) { - this.udp.on('error', async err => { - this.isWorking = false; - - callback && callback() - }); - } - - setMsgCallBack(callback) { - this.stashFn = callback ? callback : () => { - } - } - - //中心udp回执 - onMessage_2(callback, type?) { - this.udp.on('message', (value, remoteInfo) => { - let arr = [] - let dataView = new DataView(value.message) - for (let i = 0; i < dataView?.byteLength; ++i) { - arr[i] = dataView?.getUint8(i) - } - let idNum = '0x' + fillZero(arr[1].toString(16), 2) + fillZero(arr[0].toString(16), 2); - let id = Math.floor(+idNum / 1000) - - let lengthNum = '0x' + fillZero(arr[7].toString(16), 2) + fillZero(arr[6].toString(16), 2); - let length = +lengthNum; - let list = [] - for (let i = this.headLenth; i <= this.headLenth + length - 1; i++) { - list.push(arr[i]) - } - this.stashFn({ - id, - length, - body: list, - sendId: this.sendId - }) - callback({ - id, - length, - body: list, - sendId: this.sendId - }) - - - // this.interval=setInterval(()=>{ - // - // },3000) - - }); - } - - closeUdp(callback?) { - console.log('getUDPUdpClientByCenter enter closeUdp ip:' + this.localIp + ' port:' + this.localIpPort); - this.udp.close(err => { - if (err) { - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:'getUDPUdpClientByCenter closeUdp err:' + JSON.stringify(err)+this.oppositeIpPort, - // }) - } else { - this.isWorking = false - if (callback != null) { - callback() - } - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC:'getUDPUdpClientByCenter closeUdp succeed:' + JSON.stringify(err)+this.oppositeIpPort, - // }) - } - }) - } - - message_1Fn = (value) => { - let callback = this.onMessage_1Callback - // 收到的是ArrayBuffer 需要进行转换解析 - this.plcUdpError = false - if (value) { - let dataView = new DataView(value.message) - let str = "" - for (let i = 0; i < dataView?.byteLength; ++i) { - let c = String.fromCharCode(dataView?.getUint8(i)) - if (c !== "\n") { - str += c - } - } - - let strachArr = str.split(',') - if (strachArr[0] != '#DN_GD') { - return - } - - strachArr[28] = AppStorage.get('chuankoMsg') || strachArr[28] - - // this.stashFn(str) - const newArr = JSON.parse(JSON.stringify(strachArr)) - // this.writeLog({ - // time:dateFormat(new Date()), - // PLC: JSON.stringify(newArr.toString()), - // }) - if (strachArr[83] != '4') { - console.log('差分状态异常', strachArr[83], strachArr[92]) - this.writeLog({ - time: dateFormat(new Date()), - PLC: `${TAG}差分状态异常,${strachArr[83]},${strachArr[92]}`, - }) - } else { - this.chafenFlag = 0 - } - callback && callback(newArr.toString()) - this.currentValue = newArr.toString(); - } else { - callback && callback('') - } - - this.testIfUdpConnetced(callback) - } - - async writeLog(param) { - // const fileUtil = new FileUtil(globalThis.context) - // fileUtil.editFile(`${this.folderPath}/plcLog.txt`, JSON.stringify(param)+`\n`) - } - - 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 - } - - testIfUdpConnetced(callback) { - const arrRed = [0x55, 0xaa, 0x01, 0x01, 0x02, 0x00, 0x03, 0x00]; - const arrBlue = [0x55, 0xaa, 0x01, 0x00, 0x02, 0x01, 0x03, 0x00]; - const arrGreen = [0x55, 0xaa, 0x01, 0x00, 0x02, 0x00, 0x03, 0x01]; - const arrBlueBuffer = Array2Byte(arrBlue).buffer - const arrRedBuffer = Array2Byte(arrRed).buffer - const arrGreenBugger = Array2Byte(arrGreen).buffer - let num = 0 - - //监听udp是否断开 - clearInterval(this.messageTimer) - this.messageTimer = setInterval(() => { - const lightLineUdp = globalThis.lightLineUdp - const isJudge = AppStorage.get('isJudge') - setTimeout(async () => { - //程序断开 - lightLineUdp?.send(this.plcUdpError ? arrRedBuffer : (isJudge ? arrGreenBugger : arrBlueBuffer)); - if (this.plcUdpError) { - num++ - this.writeLog({ - time: dateFormat(new Date()), - PLC: 'plc udp信号丢失', - }) - console.log(TAG, 'plc udp信号丢失') - if (num == 3) { - getUDP(AppStorage.get('context'), true) - AppStorage.setOrCreate('title', 'plc udp信号丢失') - AppStorage.setOrCreate('type', 3) - num = 0 - } - - prompt.showToast({ - message: 'plc udp信号丢失', - duration: 2000 - }); - } - - this.plcUdpError = true; - }, 2000) - }, 2000) - } - - private onMessage_1Callback: Function = () => { - } - - // initHeartSendMsg(param,context){ - // console.log('1111param',JSON.stringify(param)) - // this.initParam=param - // this.context=context - // } -} - -interface StashFunction { - (params: { - id: number; - length: number; - body: any[]; - sendId: string - }): void; -} \ No newline at end of file diff --git a/entry/src/main/ets/common/utils/UdpEvent.ets b/entry/src/main/ets/common/utils/UdpEvent.ets deleted file mode 100644 index 0ebf70db..00000000 --- a/entry/src/main/ets/common/utils/UdpEvent.ets +++ /dev/null @@ -1,130 +0,0 @@ -import emitter from '@ohos.events.emitter'; - -export const EVENTID = { - //远程扣分处理 - kfEventId: 35, - //远程扣分查询 - kfAskEventId: 36, - //远程扣分确认 - kfConfirmEventId: 37, - - //远程开始考试 - beginExamEventId: 11, - //远程结束考试 - endExamEventId: 12 -} - -export default class JudgeEmitter { - private beginExamCallBack: Function = () => {} - private endExamCallBack: Function = () => {} - private confirmExamCallBack: Function = () => {} - private kfContent: Function = () => {} - - private directives: string - - constructor() { - this.init() - } - - init = async () => { - console.info('surenjun', '开始注册udp事件') - emitter.off(EVENTID.beginExamEventId) - emitter.off(EVENTID.endExamEventId) - emitter.off(EVENTID.kfConfirmEventId) - emitter.off(EVENTID.kfEventId) - - emitter.on({ - eventId: EVENTID.beginExamEventId - }, () => { - this?.beginExamCallBack() - }); - - emitter.on({ - eventId: EVENTID.endExamEventId - }, () => { - this?.endExamCallBack() - }); - - emitter.on({ - eventId: EVENTID.kfEventId - }, (data) => { - console.info('surenjun EVENTID.kfEvent' + JSON.stringify(data)) - this?.kfContent(data) - }); - - } - - //监听开始考试 - public onBeginExam = async (callBack?: Function) => { - console.info('surenjun', '注册远程开始考试事件') - this.beginExamCallBack = callBack - } - - //监听结束考试 - public onEndExam = async (callBack?: Function) => { - console.info('surenjun', '注册远程结束考试事件') - this.endExamCallBack = callBack - } - - //监听扣分处理 - public onKfExam = async (callBack?: Function) => { - console.info('surenjun', '注册远程扣分考试事件') - this.kfContent = callBack - } - - //开始考试 - public sendBeginExam = async (content: string) => { - emitter.emit({ - eventId: EVENTID.beginExamEventId - }, { - data: { - directives: content - } - }); - } - - //结束考试 - public sendEndExam = async (content: string) => { - emitter.emit({ - eventId: EVENTID.endExamEventId - }, { - data: { - directives: content - } - }); - } - - //扣分 - public sendKfContent = async (kfxh: string) => { - const directives = this.directives - console.info('surenjun', `udpEvent收到扣分事件。kfxh=>${kfxh};directives=>${directives}`) - emitter.emit({ - eventId: EVENTID.kfEventId - }, { - data: { - directives, - kfxh - } - }); - } - - //监听扣分指令 - public sendOnKf = async (directives: string) => { - //TODO 临时存储指令编号 - this.directives = directives - globalThis.judgeUdp.askKf(directives) - } - - // 获取扣分项目编号 - public onConfirmKf = async (kfxh: string) => { - const directives = this.directives; - emitter.emit({ - eventId: EVENTID.kfConfirmEventId - }, { - data: { - kfxh, directives - } - }); - } -} - diff --git a/entry/src/main/ets/common/utils/UdpJudge.ts b/entry/src/main/ets/common/utils/UdpJudge.ts deleted file mode 100644 index 36be176b..00000000 --- a/entry/src/main/ets/common/utils/UdpJudge.ts +++ /dev/null @@ -1,296 +0,0 @@ -import systemTime from '@ohos.systemDateTime'; -import { testKm2Items, testKm3Items } from '../../pages/judgeSDK/dataTest/index'; -import { judgeConfig } from '../../pages/judgeSDK/utils/judgeConfig'; -import { setJudgeUdp, setTopLineUdp } from './GlobalUdp'; -import { examCalcGpsDistance } from '../../pages/judgeSDK/api'; - -export const initJudgeUdp = async () => { - AppStorage.setOrCreate('serialIndex', 0) - AppStorage.setOrCreate('udpIndex', 0) - const udp = await setJudgeUdp() - globalThis.judgeUdp = udp - - const arrBlue = [0x55, 0xaa, 0x01, 0x00, 0x02, 0x01, 0x03, 0x00]; - const arrBlueBuffer = Array2Byte(arrBlue).buffer - - const lightLineUdp = await setTopLineUdp(); - if (lightLineUdp) { - lightLineUdp.send(arrBlueBuffer); - } - globalThis.lightLineUdp = lightLineUdp - - let [prevJd, preWd] = [0, 0] - globalThis.udpClient.onMessage_1(async (msg) => { - const stachArr = msg.split(',') - if (stachArr[0] != '#DN_GD') { - return - } - let udpIndex = AppStorage.get('udpIndex') as number; - const isJudge = AppStorage.get('isJudge'); - if (udpIndex % 5 === 0 && !isJudge) { - const bytes = await getMessageHeartbeat(msg); - const msgArr = msg.split(','); - const jd = convertGpsCoord2(msgArr[96] * 1); - const wd = convertGpsCoord2(msgArr[95] * 1 || 0); - udp.send(bytes) - if (prevJd && msgArr[83] == 4) { - const distance = await examCalcGpsDistance({ - jd1: prevJd, - wd1: preWd, - jd2: jd, - wd2: wd, - h: msgArr[90] * 1 || 1, - }) - // globalThis.distanceClass?.setTimeData(((distance / 100).toFixed(2)) * 1) - } - prevJd = jd; - preWd = wd; - } - AppStorage.setOrCreate('udpIndex', udpIndex++) - }) -} - -export const getMessageHeartbeat = async (msg) => { - const carInfo = AppStorage.get('carInfo'); - const { examSubject, plateNo } = carInfo; - const ksyh = '0000000000000' - const { fourInOneScreen:{ gpsDigit } } = judgeConfig - const asclshArr = stringToASC(fillZero( - AppStorage.get('singlePlay') - ? '1111111111111' - : AppStorage.get('lsh'), - 13)); - const ascksyhArr = stringToASC(fillZero(examSubject == 2 ? '0000000000000' : '1111111111111', 13)) - const ascsbxhArr = stringToASC('00000000') - // const ascsbxhArr = stringToASC('153216400880') - const serialIndex = AppStorage.get('serialIndex') - const tempData = await getPlcData(msg); - const examType = examSubject == 2 ? 2 : 3 - const { sensor, gps } = tempData; - const { zfxd, yfxd, shtd, ygd, jgd, skd, dh1, dh2, lhq, jsc, ssc, fsc, lb, mkg, aqd, ygq, cs, fdjzs, dw } = sensor - const { jd, wd, hxj, fyj, hbg, sd } = gps - const translateSignals = getTranslateSignals( - [zfxd, yfxd, shtd, ygd, jgd, skd, dh1, dh2, lhq, jsc, ssc, fsc, lb, mkg, aqd].concat(getDwStatusType(dw)) - .concat([0, 0, ygq, sensor.wd, 0]) - ) - const translateProject = getTranslateProject(); - const translateJd = convertGpsCoord2(wd).toFixed(gpsDigit) * Math.pow(10, gpsDigit); - const translateWd = convertGpsCoord2(jd).toFixed(gpsDigit) * Math.pow(10, gpsDigit) - const translateProjects = translateProject.map(numStr => string2Bytes(parseInt(numStr, 2), 8)[0]) - let tempSd = (sd * 1.852).toFixed(0) * 1 - if (tempSd < 1) { - tempSd = 0 - } - - const arr = [ - //考生号 - asclshArr.map(lsh => string2Bytes(lsh, 8)[0]), - //考试员号 - ascksyhArr.map(ksyh => string2Bytes(ksyh, 8)[0]), - //科目类型(0:未考试 1:科目二 2:科目三) + 考试开始时间 - string2Bytes(`${0}${'00:00:000'}`, 4 * 8), - // 消息序号 - string2Bytes(serialIndex, 2 * 8), - translateSignals, - string2Bytes(tempSd * 100, 2 * 8), string2Bytes(fdjzs / 100, 8), string2Bytes(translateJd, 4 * 8), - string2Bytes(translateWd, 4 * 8), string2Bytes(1, 8), - //GPS东向距离 - string2Bytes(0, 4 * 8), - //GPS北向距离 - string2Bytes(0, 4 * 8), - //航向角 俯仰角 高程(海拔) - string2Bytes((hxj) * 100, 2 * 8), string2Bytes(fyj * 100, 2 * 8), string2Bytes(hbg * 100, 4 * 8), - //dddd - translateProjects, - //当前项目编号 - string2Bytes(0, 8), - //场地设备编号 - ascsbxhArr.map(sbxh => string2Bytes(sbxh, 8)[0]), - //本次考试行驶距离 - string2Bytes(0, 2 * 8), - //扣分值 - string2Bytes(0, 2 * 8), - //扣分数 - string2Bytes(0, 2 * 8), - //扣分项数量 - string2Bytes(0, 8), - //n个扣分序号 - [].map(kf => string2Bytes(kf.markcatalog, 8)), - //牵引车第二gps精度、纬度 - string2Bytes(0, 4 * 8), string2Bytes(0, 4 * 8), - //牵引车第二航向角 - string2Bytes(0, 2 * 8), - //摩托压线 Byte[20], - string2Bytes(0, 20 * 8), - //考试用时 - string2Bytes(fillZero(0 + '', 4), 4 * 8), - //项目用时 - string2Bytes(fillZero(0, 2), 2 * 8), - //设备信号状态 - string2Bytes(0, 4 * 8), - ] - let tempArr = []; - arr.forEach(itemArr => { - tempArr = tempArr.concat(itemArr) - }) - - AppStorage.setOrCreate('serialIndex', 0); - return Array2Byte(tempArr) -} - -// 中心plc实时信号转换成字节 -const getTranslateSignals = (tempItems) => { - const len = Math.floor(tempItems.length / 8); - const arr = []; - for (let i = 0; i < len; i++) { - const temp = tempItems.slice(i * 8, (i + 1) * 8); - arr.push(temp.join('')); - } - const temp = arr.map(numStr => parseInt(numStr, 2)) - return temp.map(item => string2Bytes(item, 8)[0]) -} - -// 中心所有项目转换 -const getTranslateProject = () => { - const examSubject = AppStorage.get('examSubject'); - - const tempItems = (examSubject == 2 ? testKm2Items : testKm3Items).map(code => { - return { - code, status: '0' - } - }) - const arr = []; - for (let i = 0; i <= 4; i++) { - const temp = tempItems.slice(i * 4, (i + 1) * 4); - let tempArr = temp.map(item => item.status) - if (i === 4) { - tempArr = examSubject == 2 - //bit36-bit39保留 - ? tempArr.concat(['00', '00']) - //bit30-bit39保留 - : tempArr.concat(['00', '00', '00']) - } - // if (i === 3 && examSubject == 3) { - // tempArr = tempArr.concat(['00']) - // } - - arr.push(tempArr.join('')); - } - return arr -} - -// 中心实时项目状态转换 -const getCenterProjectStatus = (status) => { - switch (status) { - //不考 - case 0: - return '00' - //未考 - case 1: - return '01' - //已考 - case 2: - return '10' - } -} - -// plc数据转换成对象 -const getPlcData = async (plc: string) => { - const time = await systemTime.getCurrentTime() - const p = plc.split(',').map((val, key) => { - if (key !== 27 && key !== 92) { - return val * 1 - } else { - return val - } - }); - - const tempData = { - sensor: { - //安全带 车门门开关 手刹 脚刹 副刹 离合器 喇叭 示宽灯 近光灯 远光灯 - aqd: p[19], - mkg: p[14], - ssc: p[13], - jsc: p[12], - fsc: p[18], - lhq: p[17], - lb: p[4], - skd: p[9], - jgd: p[7], - ygd: p[8], - //左方向灯 右方向灯 双跳灯 雾灯 雨刮器 点火1 点火2 发动机转速 档位 车速 - zfxd: p[2], - yfxd: p[3], - shtd: p[20], - wd: p[10], - ygq: p[11], - dh1: p[5], - dh2: p[6], - fdjzs: p[25], - dw: p[28], - cs: p[23], - // 方向盘 - fxp: p[27].split('_')[0] * 1, - //累计脉冲 溜车脉冲 超声波左后 超声波右后 超声波右前 超声波左前 座椅 仪表盘 后视镜 倒车镜 光照 雨量 - ljmc: p[24], - lcmc: 0, - csbzh: p[32], - csbyh: p[30], - csbyq: p[31], - csbzq: p[29], - zy: 0, - tbp: 0, - hsj: 0, - dcj: 0, - gx: 0, - yl: 0 - }, - gps: { - //TODO 办卡类型 定位差分状态 - bklx: p[56], - dwzt: p[83], - //角度差分状态 - jdzt: p[92].split('-')[0] * 1, - //TODO 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], - //龄期 经度因子 纬度因子 定位搜星数 - age: p[87], - jdyz: p[89], - wdyz: p[88], - dwsxs: p[84], - // 角度搜星数 - jdsxs: p[92].split('-')[1] * 1 - }, - } - - return tempData -} - -const getDwStatusType = (dw) => { - switch (dw) { - 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] - case 9: - return [1, 0, 0, 1] - default: - return [0, 0, 0, 0] - } -} \ No newline at end of file diff --git a/entry/src/main/ets/pages/Index.ets b/entry/src/main/ets/pages/Index.ets index 8e05e130..38442c40 100644 --- a/entry/src/main/ets/pages/Index.ets +++ b/entry/src/main/ets/pages/Index.ets @@ -4,17 +4,16 @@ import router from '@ohos.router'; import { getEsCarModel, getSyncData, } from '../common/service/initable'; import { initJudgeUdp } from '../common/utils/UdpJudge'; import { judgeConfig } from './judgeSDK/utils/judgeConfig'; -import { getTCP } from '../common/utils/GlobalTcp'; import promptAction from '@ohos.promptAction'; import errorMsgDialog from './compontents/errorMsgDialog'; import imageBtn from './compontents/imageBtn'; import VoiceAnnounce from './judgeSDK/utils/voiceAnnouncements'; import { BaseInfoType, centerCallBackMsgType } from '../model/Common'; import { - CarInfoType, - InitializeTheCentralTableType, - MASYSSETTableType, - TimeSynchronizationRspBody + CarInfoType, + InitializeTheCentralTableType, + MASYSSETTableType, + TimeSynchronizationRspBody } from '../model'; import { GetCarInfo, GetDeviceInfo, SetCurrentTime, SetSerialNumber, UseAuth } from './Index/utils'; import { GetSyncData, InitializeTheCentralTable } from '../utils/table/Operation'; @@ -487,7 +486,6 @@ struct Index { } // this.loading = false this.num = 0 - // const TcpClient: TcpClient =new TcpClient(result[0].tcplocalIp, result[0].tcplocalIpPort,result[0].tcpOppositeIp,result[0].tcpOppositePort) AppStorage.setOrCreate('lsh', '1111111111111') } @@ -515,7 +513,7 @@ struct Index { await GetDeviceInfo(this.context) await GetCarInfo() // await getUDP2(this.context, false) - getTCP() + // getTCP() this.carInfo = AppStorage.get('carInfo') this.deviceId = this.carInfo.carNo // await setCurrentTime(); diff --git a/entry/src/main/ets/pages/UserInfo.ets b/entry/src/main/ets/pages/UserInfo.ets index 7f7b014e..b30b9695 100644 --- a/entry/src/main/ets/pages/UserInfo.ets +++ b/entry/src/main/ets/pages/UserInfo.ets @@ -172,7 +172,6 @@ struct UserInfo { } } - private fileUtil: FileUtils private title = '' private type = '2' errorDialog: CustomDialogController = new CustomDialogController({ @@ -467,7 +466,6 @@ struct UserInfo { } async heartMsg() { - // TODO UDP缺失 CentralHeartbeat.getData((val: centerCallBackMsgType) => { if (val.id == 32) { AppStorage.setOrCreate('signNum', val.body[1])