fix: 对接1代机

This commit is contained in:
wangzhongjie 2025-02-17 10:12:53 +08:00
parent 3d114bc468
commit a86a2a675f
11 changed files with 515 additions and 152 deletions

View File

@ -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"
}
}
}

View File

@ -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 } 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,64 @@ 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] == 11) {
console.info('surenjun', 'GlobalUdp收到beginExam事件')
globalThis.udpEvent.sendBeginExam(val.body[1])
}
if(val.body[0] == 12){
console.info('surenjun','GlobalUdp收到endExam事件')
if (val.body[0] == 12) {
console.info('surenjun', 'GlobalUdp收到endExam事件')
globalThis.udpEvent.sendEndExam(val.body[1])
}
}if (val.id == '36'){
}
if (val.id == '36') {
//获取远程扣分内容
console.info('surenjun','考车收到远程扣分项目内容,扣分代码:' + val.body[0])
console.info('surenjun', '考车收到远程扣分项目内容,扣分代码:' + val.body[0])
globalThis.udpEvent.sendKfContent(val.body[0])
} else if (val.id == '46') {
let tmpList = []
@ -225,28 +228,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 +290,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 +319,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 +350,7 @@ export async function setJudgeUdp() {
},
//申请远程扣分查询
askKf(directives){
askKf(directives) {
globalThis.udpClient2.sendMsgExt({
id: 35,
list: [directives],
@ -354,10 +361,10 @@ export async function setJudgeUdp() {
},
//确定远程扣分
confirmKf(directives,code){
confirmKf(directives, code) {
globalThis.udpClient2.sendMsgExt({
id: 37,
list: Array2Byte([string2Bytes(directives,8),string2Bytes(code,8)]),
list: Array2Byte([string2Bytes(directives, 8), string2Bytes(code, 8)]),
carNo: globalThis.carInfo.carNo,
placeId: globalThis.carInfo.examinationRoomId
})
@ -367,4 +374,5 @@ export async function setJudgeUdp() {
}
}
// globalThis.udpClient.bindUdp()

View File

@ -0,0 +1,121 @@
import socket from '@ohos.net.socket';
import { PLCGPSData } from '../../mock';
export default class UdpByOne {
// PLC udp
private PLCUDP: any;
// PLC localIp
private PLCLocalIp: string;
// PLC localIpPort
private PLCLocalIpPort: string;
// PLC oppositeIpPort
private PLCOppositeIpPort: string;
// PLC消息
private PLCMsg: string;
// GPS udp
private GPSUDP: any;
// GPS localIp
private GPSLocalIp: string;
// GPS localIpPort
private GPSLocalIpPort: string;
// GPS oppositeIpPort
private GPSOppositeIpPort: string;
// GPS消息
private GPSMsg: string;
constructor() {
// 初始化UDP
this.PLCUDP = socket.constructUDPSocketInstance();
this.PLCUDP.bind(this.PLCLocalIp, this.PLCLocalIpPort);
this.GPSUDP = socket.constructUDPSocketInstance();
this.GPSUDP.bind(this.GPSLocalIp, this.GPSLocalIpPort);
}
// 重新绑定
public rebind() {
this.PLCUDP.bind(this.PLCLocalIp, this.PLCLocalIpPort);
this.GPSUDP.bind(this.GPSLocalIp, this.GPSLocalIpPort);
}
// PLC发送消息
public sendPLCMsg(msg: string) {
this.PLCUDP.sendTo(msg, this.PLCOppositeIpPort);
}
// GPS发送消息
public sendGPSMsg(msg: string) {
this.GPSUDP.sendTo(msg, this.GPSOppositeIpPort);
}
// 接受消息
public receiveMsg(callback) {
this.GPSUDP.on("message", (message1, remoteInfo) => {
this.GPSMsg = message1;
this.PLCUDP.on("message", (message2, remoteInfo) => {
this.PLCMsg = message2;
// 组合数据
let newMessage = this.handleMsg()
callback(newMessage)
})
})
}
// 处理消息
public handleMsg() {
this.GPSMsg = `$GPGGA,021126.00,2955.5885178,N,11953.8931034,E,5,12,0.8,13.191,M,6.838,M,2.000,0000*49
$GPRMC,021126.00,A,2955.5885178,N,11953.8931034,E,4.881,318.3,170623,0.0,E,F*37
$GPGST,021126.00,3.30,1.77,3.30,0.0000,1.77,1.25,3.30*67
$PTNL,AVR,021126.00,+47.3119,Yaw,+0.4832,Tilt,,,0.817,3,1.7,25*09`
let newMessage = PLCGPSData;
// 海拔高度
// 原始GPS消息字符串
this.GPSMsg = `$GPGGA,021126.00,2955.5885178,N,11953.8931034,E,5,12,0.8,13.191,M,6.838,M,2.000,0000*49$GPRMC,021126.00,A,2955.5885178,N,11953.8931034,E,4.881,318.3,170623,0.0,E,F*37$GPGST,021126.00,3.30,1.77,3.30,0.0000,1.77,1.25,3.30*67$PTNL,AVR,021126.00,+47.3119,Yaw,+0.4832,Tilt,,,0.817,3,1.7,25*09`;
// 使用正则表达式提取$GPGGA消息
let GPGGAMsg = this.GPSMsg.match(/\$GPGGA[^$]*/)[0];
let GPGGAMsgArr = GPGGAMsg.split(',').slice(0, 15);
// 使用正则提取$GPRMC消息
let GPRMCMsg = this.GPSMsg.match(/\$GPRMC[^$]*/)[0];
let GPRMCMsgArr = GPRMCMsg.split(',').slice(0, 14);
// 使用正则表达式提取$GPGST消息]
let GPGSTMsg = this.GPSMsg.match(/\$GPGST[^$]*/)[0];
let GPGSTMsgArr = GPGSTMsg.split(',').slice(0, 9);
// 使用正则提取$PTNL消息
let PTNLMsg = this.GPSMsg.match(/\$PTNL[^$]*/)[0];
let PTNLMsgArr = PTNLMsg.split(',').slice(0, 14);
// 组合GPS数据
// 状态
// 收星数
// 海拔高
// 高度差
// 龄期
// 维度因子
// 经度因子
// 航向角
// 俯仰角
// 航向角状态-收星数
// 年月日
// 时分秒
// 经度
// 纬度
// 速度
}
// 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;
})
}
}

View File

@ -13,22 +13,19 @@
* 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 UdpByOne from './UdpByOne';
const TAG = '[UdpDemo.UdpClient]'
export default class UdpClientByCenter {
public currentValue: string = ''
private localIp: string = ''
private localIpPort: string = ''
private oppositeIp: string = ''
@ -43,15 +40,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 UPDOne: any
constructor(udplocalIp: string, udplocalIpPort: string, udpOppositeIp: string, udpOppositeIpPort: string) {
this.localIp = udplocalIp
@ -62,14 +58,14 @@ export default class UdpClientByCenter {
}
this.udp = socket.constructUDPSocketInstance();
this.initPath()
this.UPDOne = new UdpByOne()
}
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
@ -90,10 +86,10 @@ export default class UdpClientByCenter {
}).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)}`);
});
}
@ -135,9 +131,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 +143,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 +167,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 +200,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 +238,7 @@ export default class UdpClientByCenter {
this.stashFn = callback ? callback : () => {
}
}
//中心udp回执
onMessage_2(callback, type?) {
this.udp.on('message', (value, remoteInfo) => {
@ -261,14 +257,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)
@ -297,19 +298,22 @@ export default class UdpClientByCenter {
})
}
// TODO 赋值onMessage_1
//plc
onMessage_1(callback?) {
this.onMessage_1Callback = callback;
this.udp&&this.udp.on('message', this.message_1Fn);
this.UPDOne.receiveMsg(callback);
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 = (value) => {
let callback = this.onMessage_1Callback
// 收到的是ArrayBuffer 需要进行转换解析
this.plcUdpError = false
@ -336,15 +340,15 @@ 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
}
callback && callback(newArr.toString())
this.currentValue = newArr.toString();
@ -354,15 +358,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 +383,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 +396,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 +444,9 @@ export default class UdpClientByCenter {
}, 2000)
}
private onMessage_1Callback: Function = () => {
}
// initHeartSendMsg(param,context){
// console.log('1111param',JSON.stringify(param))
// this.initParam=param

View File

@ -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<void> {
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<void> {
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;
}

View File

@ -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",
];

View File

@ -1,9 +0,0 @@
export * from "./CandidateData"
export * from "./VideoData"
export * from "./Judge"
export * from "./SignDisplay"
export * from "./CarCheck"

View File

@ -6,4 +6,6 @@ export * from "./Judge"
export * from "./SignDisplay"
export * from "./CarCheck"
export * from "./CarCheck"
export * from "./PLCGPSData"

View File

@ -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"
}
}

View File

@ -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"
}
}
}