subject-two/entry/src/main/ets/common/utils/UdpClientByCenter.ts

494 lines
15 KiB
TypeScript
Raw Normal View History

2024-01-05 11:11:15 +08:00
/*
* 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.
*/
2024-07-09 13:13:59 +08:00
import socket, { UDPSocket } from '@ohos.net.socket';
2025-02-17 10:12:53 +08:00
import { Array2Byte, dateFormat, fillZero, string2Bytes } from '../utils/tools';
import FileUtil from '../../common/utils/File';
import prompt from '@ohos.prompt';
2024-08-15 09:01:09 +08:00
import promptAction from '@ohos.promptAction';
2024-08-13 11:50:38 +08:00
import { getUDP } from './GlobalUdp';
2025-03-25 10:31:44 +08:00
import RearEndUnitsTool from '../rearEndUnitsTool/index'
2025-05-20 09:32:37 +08:00
import { getCurrentTime } from '../../common/utils/tools';
2025-02-17 10:12:53 +08:00
const TAG = '[UdpDemo.UdpClient]'
2024-01-05 11:11:15 +08:00
export default class UdpClientByCenter {
2025-02-17 10:12:53 +08:00
public currentValue: string = ''
2024-07-09 13:13:59 +08:00
private localIp: string = ''
private localIpPort: string = ''
private oppositeIp: string = ''
private oppositeIpPort: string = ''
private udpMsg: any = ''
2024-08-20 09:12:02 +08:00
private chafenFlag: number = 0
2024-07-09 13:13:59 +08:00
private num: number = 0
private fileUtil: FileUtil
private udp: UDPSocket = null
private sendId: any = 0
private lsh: string = null
private context
2024-10-28 13:47:03 +08:00
private folderPath
2024-07-09 13:13:59 +08:00
private stashFn: StashFunction
2025-02-17 10:12:53 +08:00
private errorStep: number = 0
2024-08-19 09:32:41 +08:00
private interval
2024-07-09 13:13:59 +08:00
private headLenth: number = 9
//消息头长度
private isWorking: Boolean = false
private plcUdpError = false;
private initParam
2025-03-25 10:31:44 +08:00
private retClass: RearEndUnitsTool
2024-07-09 13:13:59 +08:00
constructor(udplocalIp: string, udplocalIpPort: string, udpOppositeIp: string, udpOppositeIpPort: string) {
this.localIp = udplocalIp
this.oppositeIp = udpOppositeIp
this.localIpPort = udplocalIpPort
this.oppositeIpPort = udpOppositeIpPort
this.stashFn = () => {
2024-01-05 11:11:15 +08:00
}
2024-07-09 13:13:59 +08:00
this.udp = socket.constructUDPSocketInstance();
2024-10-28 13:47:03 +08:00
this.initPath()
if (!globalThis.retClass) {
globalThis.retClass = new RearEndUnitsTool(globalThis.context)
}
this.retClass = globalThis.retClass
2025-05-20 09:32:37 +08:00
console.log(`${TAG} init UdpClientByCenter`)
2024-07-09 13:13:59 +08:00
}
getStatus() {
return this.isWorking
}
2025-02-17 10:12:53 +08:00
rebindUdp(localIp: string, localIpPort: string, oppositeIp: string, oppositeIpPort: string) {
2024-07-09 13:13:59 +08:00
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(() => {
// globalThis.closeHeartSocket=false
this.isWorking = true
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG} getUDPudp rebind success`,
// })
2025-05-20 15:33:24 +08:00
const terType = this.retClass.terType
//TODO 临时处理过滤掉中心udp
if(localIpPort != '8800' && terType == 2){
this.udp && this.udp.on('message', this.message_1Fn);
}
2024-07-09 13:13:59 +08:00
}).catch(err => {
//globalThis.closeHeartSocket=true
this.isWorking = false
2025-02-17 10:12:53 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG} getUDPudp rebind failed:${JSON.stringify(err)}`,
// })
2024-08-08 18:09:06 +08:00
console.log(`${TAG} getUDPudp rebind failed:${JSON.stringify(err)}`);
2024-07-09 13:13:59 +08:00
});
}
bindUdp() {
let promise = this.udp.bind({
address: this.localIp, port: parseInt(this.localIpPort), family: 1
});
promise.then(() => {
2025-05-20 15:33:24 +08:00
const localIpPort = this.localIpPort
2024-07-09 13:13:59 +08:00
this.isWorking = true
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG} getUDPudp bind success`,
// })
2025-05-20 15:33:24 +08:00
const terType = this.retClass.terType
//TODO 临时处理过滤掉中心udp
if(localIpPort != '8800' && terType == 2){
this.udp && this.udp.on('message', this.message_1Fn);
}
2024-07-09 13:13:59 +08:00
}).catch(err => {
this.isWorking = false
console.info('surenjun err=>', JSON.stringify(err))
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG} getUDPudp bind error${JSON.stringify(err)},localIp:${this.localIpPort},port:${this.localIpPort}`,
// })
2024-07-09 13:13:59 +08:00
});
}
//异或运算
setMessageExclusive(tmpList) {
let result = tmpList[0];
for (let i = 1; i < tmpList.length; i++) {
result = result ^ tmpList[i]
2024-07-09 11:11:31 +08:00
}
2024-07-09 13:13:59 +08:00
return [result];
}
2024-01-05 11:11:15 +08:00
2024-07-09 13:13:59 +08:00
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;
2024-01-05 11:11:15 +08:00
}
2024-07-09 13:13:59 +08:00
return view;
}
2024-07-09 11:11:31 +08:00
2024-07-09 13:13:59 +08:00
// {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
}
2025-02-17 10:12:53 +08:00
//length消息体bufferlength id消息类型id bodyStr消息体string
// setMsyBody(id,bodyByte){
setMsgHead({ id, list, placeId=62, carNo=489 }) {
2024-07-09 13:13:59 +08:00
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];
}
2025-02-17 10:12:53 +08:00
setMsgBody({ id, list }) {
2024-07-09 13:13:59 +08:00
let tmpList = []
tmpList = list
return tmpList;
}
sendHeadMsg(msgData) {
2024-08-08 18:09:06 +08:00
console.log('getUDPsendHeadMsg enter')
2024-07-09 13:13:59 +08:00
this.sendMsg(msgData, null)
2024-08-08 18:09:06 +08:00
console.log('getUDPsendHeadMsg exit')
2024-07-09 13:13:59 +08:00
}
2025-02-17 10:12:53 +08:00
sendMsg(msg, sendCallback?) {
if (!this.isWorking) {
2025-01-20 08:50:40 +08:00
// console.log(`${TAG}getUDPudpCLient sendMsg is closed return `);
2024-08-26 19:27:23 +08:00
// 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}`,
// })
2025-02-17 10:12:53 +08:00
if (sendCallback) {
2024-08-13 11:50:38 +08:00
sendCallback()
}
return;
2024-07-09 13:13:59 +08:00
}
2024-08-13 11:50:38 +08:00
let promise = this.udp.send({
data: msg,
address: {
address: this.oppositeIp,
port: parseInt(this.oppositeIpPort),
2024-07-09 13:13:59 +08:00
}
2024-08-13 11:50:38 +08:00
});
promise.then(() => {
if (sendCallback) {
sendCallback()
}
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG}getUDPudpCLient udp send success: oppositeIp:${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort:${this.localIpPort}`,
// })
2024-08-13 11:50:38 +08:00
}).catch(err => {
2024-08-26 19:27:23 +08:00
// 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({
2025-02-17 10:12:53 +08:00
message: `${TAG}getUDPudpCLient udp send fail:oppositeIp${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort,${this.localIpPort}`,
duration: 4000
})
2024-08-13 11:50:38 +08:00
});
2024-07-09 13:13:59 +08:00
}
2024-05-09 13:42:56 +08:00
2024-07-09 13:13:59 +08:00
sendMsgExt(param, context?) {
if (context) {
this.context = context
2024-01-05 11:11:15 +08:00
}
2024-07-09 13:13:59 +08:00
this.sendId = param.id
const msgData = this.setWholeMsg(param)
this.sendMsg(msgData, param.sendCallback)
}
2024-01-05 11:11:15 +08:00
2024-07-09 13:13:59 +08:00
onError_Callback(callback?) {
this.udp.on('error', async err => {
this.isWorking = false;
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:'getUDPUdpClientByCenter onError err:' + JSON.stringify(err)+this.oppositeIpPort,
// })
2024-07-09 13:13:59 +08:00
callback && callback()
});
}
2024-01-05 11:11:15 +08:00
2024-07-09 13:13:59 +08:00
onError_resend(callback?) {
this.udp.on('error', async err => {
this.isWorking = false;
2024-08-26 15:09:13 +08:00
2024-07-09 13:13:59 +08:00
callback && callback()
});
}
2024-01-05 11:11:15 +08:00
2024-07-09 13:13:59 +08:00
setMsgCallBack(callback) {
this.stashFn = callback ? callback : () => {
2024-01-05 11:11:15 +08:00
}
2024-07-09 13:13:59 +08:00
}
2025-02-17 10:12:53 +08:00
2024-07-09 13:13:59 +08:00
//中心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)
}
if (!arr.length) {
2025-04-08 13:09:28 +08:00
return
}
2024-07-09 13:13:59 +08:00
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({
2025-02-17 10:12:53 +08:00
id,
length,
body: list,
sendId: this.sendId
2024-07-09 13:13:59 +08:00
})
callback({
2025-02-17 10:12:53 +08:00
id,
length,
body: list,
sendId: this.sendId
2024-07-09 13:13:59 +08:00
})
2025-01-20 08:50:40 +08:00
2024-10-28 13:47:03 +08:00
2024-08-20 09:12:02 +08:00
// this.interval=setInterval(()=>{
//
// },3000)
2024-08-19 09:32:41 +08:00
2024-07-09 13:13:59 +08:00
});
}
2024-01-05 11:11:15 +08:00
2024-07-09 13:13:59 +08:00
closeUdp(callback?) {
2024-08-08 18:09:06 +08:00
console.log('getUDPUdpClientByCenter enter closeUdp ip:' + this.localIp + ' port:' + this.localIpPort);
2024-07-09 13:13:59 +08:00
this.udp.close(err => {
if (err) {
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:'getUDPUdpClientByCenter closeUdp err:' + JSON.stringify(err)+this.oppositeIpPort,
// })
2024-07-09 13:13:59 +08:00
} else {
2024-07-16 17:23:42 +08:00
this.isWorking = false
if (callback != null) {
callback()
}
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:'getUDPUdpClientByCenter closeUdp succeed:' + JSON.stringify(err)+this.oppositeIpPort,
// })
2024-07-09 13:13:59 +08:00
}
})
}
2024-07-09 11:11:31 +08:00
2024-07-09 13:13:59 +08:00
//plc
onMessage_1(callback?) {
const terType = globalThis.retClass?.terType;
if (terType == 2) {
//三型机
this.onMessage_1Callback = callback;
} else {
this.retClass.receiveMsg(callback)
2025-05-20 09:32:37 +08:00
//TODO 临时处理
globalThis.retClass = this.retClass
}
2025-05-20 09:32:37 +08:00
2025-02-21 15:22:23 +08:00
// this.udp && this.udp.on('message', this.message_1Fn);
2024-08-05 09:47:44 +08:00
}
2024-06-27 20:53:36 +08:00
2025-02-17 10:12:53 +08:00
closeMessage_1() {
2024-08-08 18:09:06 +08:00
console.info('surenjun', 'getUDP关闭udp message监听事件')
2025-02-17 10:12:53 +08:00
this.udp.off('message', this.message_1Fn);
2024-08-08 18:09:06 +08:00
console.info('surenjun', 'getUDP关闭udp message监听事件 成功')
2024-08-05 09:47:44 +08:00
}
2024-01-05 11:11:15 +08:00
2025-05-20 09:32:37 +08:00
message_1Fn = async (value) => {
// console.info('surenjun2','set message_1Fn=>' + await getCurrentTime())
2024-08-05 09:47:44 +08:00
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
}
}
2024-07-09 13:13:59 +08:00
2024-08-05 09:47:44 +08:00
let strachArr = str.split(',')
if (strachArr[0] != '#DN_GD') {
return
2024-07-09 13:13:59 +08:00
}
2024-08-05 09:47:44 +08:00
2024-08-08 18:09:06 +08:00
strachArr[28] = globalThis.chuankoMsg || strachArr[28]
2024-08-20 09:12:02 +08:00
2024-08-05 09:47:44 +08:00
// this.stashFn(str)
const newArr = JSON.parse(JSON.stringify(strachArr))
2024-11-20 13:44:40 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC: JSON.stringify(newArr.toString()),
// })
2025-02-17 10:12:53 +08:00
if (strachArr[83] != '4') {
console.log('差分状态异常', strachArr[83], strachArr[92])
2024-11-20 13:44:40 +08:00
this.writeLog({
2025-02-17 10:12:53 +08:00
time: dateFormat(new Date()),
2024-11-20 13:44:40 +08:00
PLC: `${TAG}差分状态异常,${strachArr[83]},${strachArr[92]}`,
})
2025-02-17 10:12:53 +08:00
} else {
globalThis.dialogOpen = false
this.chafenFlag = 0
2024-08-20 09:12:02 +08:00
}
2025-05-20 09:32:37 +08:00
// console.info('surenjun2','set message_1Fn=>' + newArr.toString())
callback && callback(newArr.toString())
2025-05-20 09:32:37 +08:00
console.info('surenjun 左方向灯=>', newArr.toString())
2024-08-05 09:47:44 +08:00
this.currentValue = newArr.toString();
} else {
callback && callback('')
}
2024-08-20 09:12:02 +08:00
2024-08-05 09:47:44 +08:00
this.testIfUdpConnetced(callback)
}
2025-02-17 10:12:53 +08:00
async writeLog(param) {
2024-12-29 21:43:12 +08:00
// const fileUtil = new FileUtil(globalThis.context)
// fileUtil.editFile(`${this.folderPath}/plcLog.txt`, JSON.stringify(param)+`\n`)
2024-10-28 13:47:03 +08:00
}
2025-02-17 10:12:53 +08:00
async initPath() {
2024-12-29 21:43:12 +08:00
// const fileUtil = new FileUtil(globalThis.context)
// const date=dateFormat(new Date).split(' ')[0]
// this.folderPath = await fileUtil.initFolder(`/PLC/${date}`);
2024-08-20 09:12:02 +08:00
}
2025-02-17 10:12:53 +08:00
2024-08-05 09:47:44 +08:00
//获取当前UDP信号
getCurrentMessage = () => {
return this.currentValue
2024-07-09 13:13:59 +08:00
}
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
2025-02-17 10:12:53 +08:00
globalThis.dialogOpen = false
2024-08-20 09:12:02 +08:00
2024-07-09 13:13:59 +08:00
//监听udp是否断开
clearInterval(globalThis.messageTimer)
globalThis.messageTimer = setInterval(() => {
const lightLineUdp = globalThis.lightLineUdp
const isJudge = globalThis.isJudge
setTimeout(async () => {
//程序断开
lightLineUdp?.send(this.plcUdpError ? arrRedBuffer : (isJudge ? arrGreenBugger : arrBlueBuffer));
if (this.plcUdpError) {
num++
2024-10-28 13:47:03 +08:00
this.writeLog({
2025-02-17 10:12:53 +08:00
time: dateFormat(new Date()),
2024-10-28 13:47:03 +08:00
PLC: 'plc udp信号丢失',
})
2024-07-09 13:13:59 +08:00
console.log(TAG, 'plc udp信号丢失')
if (num == 3) {
2025-02-17 10:12:53 +08:00
getUDP(globalThis.context, true)
globalThis.title = 'plc udp信号丢失'
globalThis.type = '3'
if (!globalThis.dialogOpen) {
2024-08-23 13:44:42 +08:00
// AppStorage.SetOrCreate('errorCode', 1);
// if(this.errorStep!=1){
// console.log('sys.v_valuesys.v_valuesys.v_value11221')
//
// this.errorStep=1
// this.avPlayer.playAudio(['voice/差分状态异常.wav'])
// getSyncData('MA_SYSSET').then(syssetParams => {
// console.log('sys.v_valuesys.v_valuesys.v_value11221',JSON.stringify(syssetParams))
// // @ts-ignore
// syssetParams.forEach(sys => {
// // 差分长时间是SINGLE状态报考车故障,停止考试0-否 1-是)
// if (sys.v_no === '424'&&sys.v_value==1){
// //plc差分丢失
// AppStorage.SetOrCreate('errorCode', 0);
// AppStorage.SetOrCreate('errorCodeFlage', true);
//
// }
// })
// // const errorParam = syssetParams.filter(sys => sys.v_no === '424') //
// // that.studentRefreshStatue = studentRefreshParam?.[0]?.v_value || '0'
//
//
// });
// }
2024-08-20 09:43:25 +08:00
}
2024-07-09 13:13:59 +08:00
num = 0
}
2024-08-20 09:43:25 +08:00
2024-07-09 13:13:59 +08:00
prompt.showToast({
message: 'plc udp信号丢失',
duration: 2000
});
}
2024-08-20 09:12:02 +08:00
2024-07-09 13:13:59 +08:00
this.plcUdpError = true;
}, 2000)
2024-08-20 09:43:25 +08:00
}, 2000)
2024-07-09 13:13:59 +08:00
}
2025-02-17 10:12:53 +08:00
private onMessage_1Callback: Function = () => {
}
2024-07-09 13:13:59 +08:00
// initHeartSendMsg(param,context){
// console.log('1111param',JSON.stringify(param))
// this.initParam=param
// this.context=context
// }
2024-03-12 15:32:48 +08:00
}
2024-07-09 13:13:59 +08:00
2024-03-12 15:32:48 +08:00
interface StashFunction {
2024-07-09 13:13:59 +08:00
(params: {
id: number;
length: number;
body: any[];
sendId: string
}): void;
2024-01-05 11:11:15 +08:00
}