diff --git a/entry/src/main/ets/common/utils/UdpClient.ts b/entry/src/main/ets/common/utils/UdpClient.ts deleted file mode 100644 index 0fe7d78f..00000000 --- a/entry/src/main/ets/common/utils/UdpClient.ts +++ /dev/null @@ -1,237 +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. - */ - -import socket from '@ohos.net.socket'; -import { Array2Byte } from '../utils/tools' -import {getChuankouFn} from '../../common/service/indexService' -import {getUDP} from './GlobalUdp' -const TAG = 'socketTag[PLC.UdpClient]' -import prompt from '@ohos.prompt' - -import hilog from '@ohos.hilog'; -let num=0 -export default class UdpClient { - private localIp: string = '' - private localIpPort: string = '' - private oppositeIp: string = '' - private oppositeIpPort: string = '' - - private udp: any = null - // private stashFn:StashFuncotionon - - constructor(udplocalIp: string, udplocalIpPort: string, udpOppositeIp: string, udpOppositeIpPort: string) { - this.localIp = udplocalIp - this.oppositeIp = udpOppositeIp - this.localIpPort = udplocalIpPort - this.oppositeIpPort = udpOppositeIpPort - getChuankouFn() - console.log(TAG,'newUdp') - // this.stashFn=()=>{} - this.udp = socket.constructUDPSocketInstance(); - } - - rebindUdp(localIp: string, localIpPort: string, oppositeIp: string, oppositeIpPort: string) { - console.log(TAG,'rebindUdp',this.localIp,this.localIpPort) - - this.localIp = localIp - this.oppositeIp = oppositeIp - this.localIpPort = localIpPort - this.oppositeIpPort = oppositeIpPort - let promise = this.udp.bind({ - address: this.localIp, port: parseInt(this.localIpPort), family: 1 - }); - promise.then(() => { - globalThis.closeUDPSocket=false - - console.log(`${TAG},udpCLient udp rebind success`); - }).catch(err => { - globalThis.closeUDPSocket=true - console.log(`${TAG},udpCLient udp rebind failed:${JSON.stringify(err)}`); - }); - } - - bindUdp() { - console.log(TAG,'udpbind',this.localIp,this.localIpPort) - let promise = this.udp.bind({ - // address: '192.168.7.170', port: 20122, family: 1 - // address: '192.168.7.170', port: 31013, family: 1 - address: this.localIp, port: parseInt(this.localIpPort), family: 1 - }); - promise.then(() => { - globalThis.closeUDPSocket=false - console.log(`${TAG}udpCLient udp bind success`); - }).catch(err => { - globalThis.closeUDPSocket=true - console.log(`${TAG}udpCLient udp bind failed:${JSON.stringify(err)}`); - }); - } - setMsgCallBack(callback){ - // this.stashFn=callback?callback:()=>{} - } - sendMsg(msg) { - console.log(TAG,'UdpSend1111',this.oppositeIp,this.oppositeIpPort) - this.udp.getState((err, data) => { - if (err) { - - console.log('getState fail'); - return; - } else { - let promise = this.udp.send({ - data: msg, - address: { - // address: '192.168.7.124', - // port: 30013, - // address: '192.168.7.124', - // port: 20022, - address: this.oppositeIp, - port: parseInt(this.oppositeIpPort), - family: 1 - } - }); - promise.then(() => { - console.log(`${TAG}udpCLient udp send success:oppositeIp${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort,${this.localIpPort}`); - }).catch(err => { - console.log(`${TAG}udpCLient udp send fail:oppositeIp${this.oppositeIp},oppositeIpPort:${this.oppositeIpPort},localIp:${this.localIp},localIpPort,${this.localIpPort}`); - }); - } - console.log('getState success:' + JSON.stringify(data)); - }) - - } - onError(callback?){ - this.udp.on('error',async err => { - globalThis.closeUDPSocket=true - console.log(TAG,'udpError',JSON.stringify(err)) - await this.bindUdp() - await this.sendMsg('111') - await this.onMessage(callback) - // callback&&callback() - // this.closeUdp(()=>{ - // this.bindUdp() - // }) - }); - } - - onMessage(callback?) { - console.info(TAG, '注册udp message监听事件') - this.udp.on('message', value => { - console.log(TAG,'udponmessage') - // 收到的是ArrayBuffer 需要进行转换解析 - globalThis.plcUdpError = false - if (value) { - - let dataView = new DataView(value.message) - // console.log(`${TAG} udp message length:${dataView?.byteLength}`); - let str = "" - for (let i = 0; i < dataView?.byteLength; ++i) { - let c = String.fromCharCode(dataView?.getUint8(i)) - if (c !== "\n") { - str += c - } - } - - console.log(`${TAG} udp on message array buffer:${str}`); - let strachArr = str.split(',') - if (strachArr[0] != '#DN_GD') { - return - } - console.log(`${TAG} udp222 on message array buffer:${str}`); - - strachArr[28]=globalThis.chuankoMsg||'0' - // this.stashFn(str) - const newArr=JSON.parse(JSON.stringify(strachArr)) - // this.stashFn=()=>{} - callback&&callback(newArr.toString()) - - } else { - callback&&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 - //监听udp是否断开 - clearInterval(globalThis.messageTimer) - globalThis.messageTimer = setInterval(() => { - const lightLineUdp = globalThis.lightLineUdp - const isJudge = globalThis.isJudge - setTimeout(async () => { - //程序断开 - lightLineUdp?.send(globalThis.plcUdpError ? arrRedBuffer : (isJudge ? arrGreenBugger : arrBlueBuffer)); - if (globalThis.plcUdpError) { - // num++ - console.log(TAG,'plc udp信号丢失') - // if(num==3){ - getUDP(globalThis.context,true) - // await this.bindUdp() - // await this.sendMsg('111') - // await this.onMessage(callback) - // num=0 - // } - prompt.showToast({ - message: 'plc udp信号丢失', - duration: 2000 - }); - } - globalThis.plcUdpError = true; - }, 2000) - }, 3000) - } - - closeUdp(callback) { - this.udp.close(err => { - hilog.info(0x0000,TAG, 'udpCLient', 'close'); - - if (err) { - hilog.info(0x0000,TAG, 'udpCLient', 'closeonerror'); - globalThis.closeUDPSocket=false - - } else { - globalThis.closeUDPSocket=true - - this.udp.getState((err, data) => { - if (err) { - console.log('getState fail'); - return; - } else { - if (!data.isisClose) { - setTimeout(() => { - callback() - }, 1000) - } - } - console.log('getState success:' + JSON.stringify(data)); - }) - // let promise = this.udp.getState({}); - // promise.then(data => { - // - // console.log('getState success:' + JSON.stringify(data)); - // }).catch(err => { - // callback() - // console.log('getState fail'); - // }); - } - }); - } - - -} -interface StashFunction { - (str: string) -} \ No newline at end of file diff --git a/entry/src/main/ets/pages/compontents/SignDisplayCom.ets b/entry/src/main/ets/pages/compontents/SignDisplayCom.ets index 60dbe634..acb9a588 100644 --- a/entry/src/main/ets/pages/compontents/SignDisplayCom.ets +++ b/entry/src/main/ets/pages/compontents/SignDisplayCom.ets @@ -1,5 +1,4 @@ import router from '@ohos.router'; -import UdpClient from '../../common/utils/UdpClient'; import FileLog from '../judgeSDK/utils/fileLog'; import RealTime from '../compontents/judge/RealTime'; import { GPSData, SignalData } from '../../mock'; @@ -24,7 +23,6 @@ export default struct SignDisplayCom { @State @Watch('outClick') outFlag: boolean = false; @State url: string = '' private timer = null - private udpClient: UdpClient = null private FileLog: FileLog private vocObj = null; diff --git a/entry/src/main/ets/pages/compontents/SignDisplayCom2.ets b/entry/src/main/ets/pages/compontents/SignDisplayCom2.ets index 4e766772..a422cf11 100644 --- a/entry/src/main/ets/pages/compontents/SignDisplayCom2.ets +++ b/entry/src/main/ets/pages/compontents/SignDisplayCom2.ets @@ -1,5 +1,4 @@ import router from '@ohos.router'; -import UdpClient from '../../common/utils/UdpClient'; import FileLog from '../judgeSDK/utils/fileLog'; import RealTime from '../compontents/judge/RealTime'; import { GPSData, SignalData } from '../../mock'; @@ -23,7 +22,6 @@ export default struct SignDisplayCom { @State @Watch('outClick') outFlag: boolean = false; @State url: string = '' private timer = null - private udpClient: UdpClient = null private FileLog: FileLog private vocObj = null; diff --git a/entry/src/main/ets/utils/UdpUtils.ets b/entry/src/main/ets/utils/UdpUtils.ets new file mode 100644 index 00000000..ec48e71b --- /dev/null +++ b/entry/src/main/ets/utils/UdpUtils.ets @@ -0,0 +1,75 @@ +import socket from '@ohos.net.socket' + +type DealMethod = (value: ArrayBuffer) => string + +class UdpClient { + private localIp: string = '' + private localIpPort: string = '' + private oppositeIp: string = '' + private oppositeIpPort: string = '' + private messageEvents: Array = [] + private udp: socket.UDPSocket = null + private disconnectEvents: Array = [] + private dealMethod: DealMethod + + private dealMessage() { + this.udp?.on("message", value => { + let result = this?.dealMethod(value.message) + this.messageEvents.forEach(cb => { + cb(result) + }) + }) + } + + init(udpLocalIp: string, udpLocalIpPort: string, udpOppositeIp: string, udpOppositeIpPort: string) { + this.localIp = udpLocalIp + this.oppositeIp = udpOppositeIp + this.localIpPort = udpLocalIpPort + this.oppositeIpPort = udpOppositeIpPort + this.udp = socket.constructUDPSocketInstance(); + } + + bindUdp(): Promise { + return this.udp.bind({ address: this.localIp, port: parseInt(this.localIpPort), family: 1 }).then(() => { + try { + this.dealMessage() + return Promise.resolve() + } catch (e) { + return Promise.reject(e) + } + }) + } + + async reBind() { + await this.close() + this.udp = socket.constructUDPSocketInstance(); + await this.bindUdp() + } + + close(): Promise { + return this.udp?.close() + } + + setDealMethod(fun: DealMethod) { + this.dealMethod = fun + } + + onMessage(callback: Function) { + this.messageEvents.push(callback) + } + + onDisconnect(callback: Function) { + this.disconnectEvents.push(callback) + } + + sendMsg(data: string): Promise { + return this.udp?.getState().then(() => { + return this.udp.send({ + data, + address: { address: this.oppositeIp, port: parseInt(this.oppositeIpPort), family: 1 } + }) + }) + } +} + +export const udpClient = new UdpClient() \ No newline at end of file