GlobalUdp.ts 优化 #13
| @ -1,98 +1,232 @@ | ||||
| import UdpClient from './UdpClient'; | ||||
| import UdpClientByCenter from './UdpClientByCenter'; | ||||
| import { getSyncData} from '../service/initable' | ||||
| import { dateFormat } from '../../common/utils/tools' | ||||
| import prompt from '@ohos.prompt' | ||||
| import TcpClient from './TcpClient'; | ||||
| import {string2Bytes} from '../../common/utils/tools' | ||||
| export async function sendMsg(val){ | ||||
|   // globalThis.udpClient1&&globalThis.udpClient1.sendMsg(val)
 | ||||
| import { getSyncData } from '../service/initable' | ||||
| import { fillZero, string2Bytes } from '../utils/tools' | ||||
| 
 | ||||
| interface UdpOption { | ||||
|   udplocalIp: string | ||||
|   udplocalIpPort: string | ||||
|   udpOppositeIp: string | ||||
|   udpOppositeIpPort: string | ||||
| } | ||||
| export async function getUDP(flag:Boolean=false) { | ||||
|   getSyncData('IpConfigTable').then((result:Array<any>)=>{ | ||||
|     if(result.length){ | ||||
|       if(!flag){ | ||||
| 
 | ||||
| export default class UdpUtils { | ||||
|   private static config: UdpOption | ||||
| 
 | ||||
|   public static async getConfig() { | ||||
|     this.config = ((await getSyncData("IpConfigTable")) as Array<any> || [])[0] | ||||
|   } | ||||
| 
 | ||||
|   public static async createUdpClient(client: UdpClient | UdpClientByCenter, udpConfig: UdpOption, type: string, onMessage?: Function) { | ||||
|     if (!this.config) { | ||||
|       return [{ | ||||
|         onMessage: () => { | ||||
|         } | ||||
|       }, ""] | ||||
|     } | ||||
|     if (client) { | ||||
|       await client.closeUdp() | ||||
|       client.rebindUdp(udpConfig.udplocalIp, udpConfig.udplocalIpPort, udpConfig.udpOppositeIp, udpConfig.udpOppositeIpPort) | ||||
|     } else { | ||||
|       if (type === "1") { | ||||
|         client = new UdpClient(udpConfig.udplocalIp, udpConfig.udplocalIpPort, udpConfig.udpOppositeIp, udpConfig.udpOppositeIpPort) | ||||
|       } else { | ||||
|         client = new UdpClientByCenter(udpConfig.udplocalIp, udpConfig.udplocalIpPort, udpConfig.udpOppositeIp, udpConfig.udpOppositeIpPort) | ||||
|       } | ||||
|       client.bindUdp() | ||||
|     } | ||||
|     if (type === "1") { | ||||
|       client.sendMsg("111") | ||||
|     } | ||||
|     client.onMessage(onMessage || (() => { | ||||
|     })) | ||||
|     client.onError(client.onMessage || (() => { | ||||
|     })) | ||||
|     return [client, `http://${this.config[0].centerIp}:${this.config[0].centerPort}`] | ||||
|   } | ||||
| 
 | ||||
|   public static async getUdp(client: UdpClient) { | ||||
|     return this.createUdpClient(client, { | ||||
|       udplocalIp: this.config.udplocalIp, | ||||
|       udplocalIpPort: this.config.udplocalIpPort, | ||||
|       udpOppositeIp: this.config.udpOppositeIp, | ||||
|       udpOppositeIpPort: this.config.udpOppositeIpPort | ||||
|     }, "1") | ||||
|   } | ||||
| 
 | ||||
|   public static async getUdp2(client: UdpClient) { | ||||
|     return this.createUdpClient(client, { | ||||
|       udplocalIp: this.config.udplocalIp, | ||||
|       udplocalIpPort: "8800", | ||||
|       udpOppositeIp: globalThis.carInfo?.udpAddress, | ||||
|       udpOppositeIpPort: globalThis.carInfo?.messagePort | ||||
|     }, "2", (val) => { | ||||
|       if (val.id == '32') { | ||||
|         globalThis.signNum = val.body[1] | ||||
| 
 | ||||
|       } else if (val.id == '46') { | ||||
|         let tmpList = [] | ||||
|         const str = globalThis.lsh | ||||
|         for (let i = 0; i < str.length; i++) { | ||||
|           tmpList.push(string2Bytes(str.charCodeAt(i), 1 * 8)[0]) | ||||
|         } | ||||
|         const param = { | ||||
|           id: 47, | ||||
|           list: tmpList, | ||||
|           carNo: globalThis.carInfo.carNo, | ||||
|           placeId: globalThis.carInfo.examinationRoomId | ||||
|         } | ||||
|         globalThis.udpClient2.send(param) | ||||
|       } | ||||
|     }) | ||||
|   } | ||||
| 
 | ||||
|   public static async setTopLineUdp() { | ||||
|     if (this.config && this.config.udplocalIp) { | ||||
|       const {udplocalIp,udpOppositeIp,udpOppositeIpPort} = this.config; | ||||
|       const udpClient: UdpClientByCenter = new UdpClientByCenter(udplocalIp, '55509', udpOppositeIp, udpOppositeIpPort) | ||||
|       udpClient.bindUdp() | ||||
|       return { | ||||
|         send(bytes) { | ||||
|           udpClient.sendHeadMsg(bytes) | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
|   public static async setJudgeUdp() { | ||||
|     let udpIndex = 0; | ||||
|     let currentUdpIndex = 0; | ||||
|     let judgeUdpTimer | ||||
|     clearInterval(judgeUdpTimer) | ||||
|     judgeUdpTimer = setInterval(() => { | ||||
|       udpIndex += 1; | ||||
|     }, 1000); | ||||
| 
 | ||||
|     if (this.config && this.config.udplocalIp) { | ||||
|       const {udplocalIp} = this.config; | ||||
|       const udpClient: UdpClientByCenter = new UdpClientByCenter(udplocalIp, '8080', globalThis.carInfo?.gpsAddress, globalThis.carInfo?.hintPort) | ||||
|       udpClient.bindUdp() | ||||
|       udpClient.onMessage((val) => { | ||||
|         console.log('valval', val) | ||||
|       }) | ||||
|       globalThis.judgeUdpClient = udpClient; | ||||
|       return { | ||||
|         send(bytes) { | ||||
|           if (udpIndex > currentUdpIndex) { | ||||
|             udpClient.sendMsg({ | ||||
|               id: 45, | ||||
|               list: bytes, | ||||
|               carNo: globalThis.carInfo.carNo, | ||||
|               placeId: globalThis.carInfo.examinationRoomId | ||||
|             }) | ||||
|             currentUdpIndex = udpIndex | ||||
|           } | ||||
|         } | ||||
|       } | ||||
|     } | ||||
|   } | ||||
| } | ||||
| 
 | ||||
| export async function sendMsg(val) { | ||||
| } | ||||
| 
 | ||||
| export async function getUDP(flag: Boolean = false) { | ||||
|   getSyncData('IpConfigTable').then((result: Array<any>) => { | ||||
|     if (result.length) { | ||||
|       if (!flag) { | ||||
|         return | ||||
|       } | ||||
|       if(globalThis.udpClient&&globalThis.udpClient.closeUdp){ | ||||
|         globalThis.udpClient.closeUdp(()=>{ | ||||
|           globalThis.udpClient.rebindUdp(result[0].udplocalIp, result[0].udplocalIpPort,result[0].udpOppositeIp,result[0].udpOppositeIpPort) | ||||
|       if (globalThis.udpClient && globalThis.udpClient.closeUdp) { | ||||
|         globalThis.udpClient.closeUdp(() => { | ||||
|           globalThis.udpClient.rebindUdp(result[0].udplocalIp, result[0].udplocalIpPort, result[0].udpOppositeIp, result[0].udpOppositeIpPort) | ||||
|           globalThis.udpClient.sendMsg('111') | ||||
|           globalThis.host=`http://${result[0].centerIp}:${result[0].centerPort}` | ||||
|           globalThis.udpClient.onError(globalThis.udpClient.onMessage?globalThis.udpClient.onMessage:()=>{}) | ||||
|           globalThis.host = `http://${result[0].centerIp}:${result[0].centerPort}` | ||||
|           globalThis.udpClient.onError(globalThis.udpClient.onMessage ? globalThis.udpClient.onMessage : () => { | ||||
|           }) | ||||
| 
 | ||||
|         }) | ||||
|       }else{ | ||||
|       } else { | ||||
| 
 | ||||
|         const udpClient: UdpClient =new UdpClient(result[0].udplocalIp, result[0].udplocalIpPort,result[0].udpOppositeIp,result[0].udpOppositeIpPort) | ||||
|         const udpClient: UdpClient = new UdpClient(result[0].udplocalIp, result[0].udplocalIpPort, result[0].udpOppositeIp, result[0].udpOppositeIpPort) | ||||
|         udpClient.bindUdp() | ||||
|         udpClient.sendMsg('111') | ||||
|         globalThis.udpClient = udpClient | ||||
|         globalThis.host=`http://${result[0].centerIp}:${result[0].centerPort}` | ||||
|         globalThis.udpClient.onError(globalThis.udpClient.onMessage?globalThis.udpClient.onMessage:()=>{}) | ||||
|         globalThis.host = `http://${result[0].centerIp}:${result[0].centerPort}` | ||||
|         globalThis.udpClient.onError(globalThis.udpClient.onMessage ? globalThis.udpClient.onMessage : () => { | ||||
|         }) | ||||
| 
 | ||||
|       } | ||||
| 
 | ||||
|     }else{ | ||||
|       globalThis.udpClient={} | ||||
|       globalThis.udpClient.onMessage=()=>{} | ||||
|       globalThis.host='' | ||||
|     } else { | ||||
|       globalThis.udpClient = {} | ||||
|       globalThis.udpClient.onMessage = () => { | ||||
|       } | ||||
|       globalThis.host = '' | ||||
|     } | ||||
|   }) | ||||
| } | ||||
| 
 | ||||
| export async function getUDP2(flag:Boolean=false) { | ||||
|   getSyncData('IpConfigTable').then(async (result:Array<any>)=>{ | ||||
|     if(result.length){ | ||||
|       if(globalThis.udpClient2&&globalThis.udpClient2.closeUdp){ | ||||
|         if(!flag){ | ||||
| export async function getUDP2(flag: Boolean = false) { | ||||
|   getSyncData('IpConfigTable').then(async (result: Array<any>) => { | ||||
|     if (result.length) { | ||||
|       if (globalThis.udpClient2 && globalThis.udpClient2.closeUdp) { | ||||
|         if (!flag) { | ||||
|           return | ||||
|         } | ||||
|         globalThis.udpClient2.closeUdp(async ()=>{ | ||||
|           globalThis.udpClient2.rebindUdp(result[0].udplocalIp, '8800',globalThis.carInfo?.udpAddress,globalThis.carInfo?.messagePort) | ||||
|           globalThis.udpClient2.onMessage((val)=>{ | ||||
|         globalThis.udpClient2.closeUdp(async () => { | ||||
|           globalThis.udpClient2.rebindUdp(result[0].udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) | ||||
|           globalThis.udpClient2.onMessage((val) => { | ||||
|           }) | ||||
|           globalThis.udpClient2.onError() | ||||
|           globalThis.udpClient2.setMsgCallBack=()=>{} | ||||
|           globalThis.udpClient2.setMsgCallBack = () => { | ||||
|           } | ||||
| 
 | ||||
|         }) | ||||
|       }else{ | ||||
|         const udpClient: UdpClientByCenter =new UdpClientByCenter(result[0].udplocalIp, '8800',globalThis.carInfo?.udpAddress,globalThis.carInfo?.messagePort) | ||||
|       } else { | ||||
|         const udpClient: UdpClientByCenter = new UdpClientByCenter(result[0].udplocalIp, '8800', globalThis.carInfo?.udpAddress, globalThis.carInfo?.messagePort) | ||||
|         globalThis.udpClient2 = udpClient | ||||
|         globalThis.udpClient2.bindUdp() | ||||
|         globalThis.udpClient2.onError() | ||||
|         globalThis.udpClient2.onMessage((val)=>{ | ||||
|           if(val.id=='32'){ | ||||
|             globalThis.signNum=val.body[1] | ||||
|         globalThis.udpClient2.onMessage((val) => { | ||||
|           if (val.id == '32') { | ||||
|             globalThis.signNum = val.body[1] | ||||
| 
 | ||||
|           }else if(val.id=='46'){ | ||||
|           } else if (val.id == '46') { | ||||
|             let tmpList = [] | ||||
|             const str = globalThis.lsh | ||||
|             for (let i = 0;i < str.length; i++) { | ||||
|             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: globalThis.carInfo.carNo, placeId: globalThis.carInfo.examinationRoomId } | ||||
|             const param = { | ||||
|               id: 47, | ||||
|               list: tmpList, | ||||
|               carNo: globalThis.carInfo.carNo, | ||||
|               placeId: globalThis.carInfo.examinationRoomId | ||||
|             } | ||||
|             globalThis.udpClient2.send(param) | ||||
|           } | ||||
|         }) | ||||
|       } | ||||
|     }else{ | ||||
|       globalThis.udpClient2={} | ||||
|       globalThis.udpClient2.onMessage=()=>{} | ||||
|       globalThis.udpClient2.setMsgCallBack=()=>{} | ||||
|     } else { | ||||
|       globalThis.udpClient2 = {} | ||||
|       globalThis.udpClient2.onMessage = () => { | ||||
|       } | ||||
|       globalThis.udpClient2.setMsgCallBack = () => { | ||||
|       } | ||||
|     } | ||||
|   }) | ||||
| } | ||||
| 
 | ||||
| export async function setTopLineUdp(){ | ||||
| export async function setTopLineUdp() { | ||||
|   const config = await getSyncData('IpConfigTable'); | ||||
|   if(config && config[0] && config[0].udplocalIp){ | ||||
|   if (config && config[0] && config[0].udplocalIp) { | ||||
|     const {udplocalIp,udpOppositeIp,udpOppositeIpPort} = config[0]; | ||||
|     const udpClient: UdpClientByCenter = new UdpClientByCenter(udplocalIp, '55509',udpOppositeIp,udpOppositeIpPort) | ||||
|     const udpClient: UdpClientByCenter = new UdpClientByCenter(udplocalIp, '55509', udpOppositeIp, udpOppositeIpPort) | ||||
|     udpClient.bindUdp() | ||||
| 
 | ||||
|     return { | ||||
|       send(bytes){ | ||||
|       send(bytes) { | ||||
|         udpClient.sendHeadMsg(bytes) | ||||
|       } | ||||
|     } | ||||
| @ -100,29 +234,34 @@ export async function setTopLineUdp(){ | ||||
| } | ||||
| 
 | ||||
| //
 | ||||
| export async function setJudgeUdp(){ | ||||
| export async function setJudgeUdp() { | ||||
|   const config = await getSyncData('IpConfigTable'); | ||||
| 
 | ||||
|   let udpIndex = 0; | ||||
|   let currentUdpIndex = 0; | ||||
|   let judgeUdpTimer | ||||
|   clearInterval(judgeUdpTimer) | ||||
|    judgeUdpTimer = setInterval(()=>{ | ||||
|   judgeUdpTimer = setInterval(() => { | ||||
|     udpIndex += 1; | ||||
|   },1000); | ||||
|   }, 1000); | ||||
| 
 | ||||
|   if(config && config[0] && config[0].udplocalIp){ | ||||
|   if (config && config[0] && config[0].udplocalIp) { | ||||
|     const {udplocalIp} = config[0]; | ||||
|     const udpClient: UdpClientByCenter = new UdpClientByCenter(udplocalIp, '8080',globalThis.carInfo?.gpsAddress,globalThis.carInfo?.hintPort) | ||||
|     const udpClient: UdpClientByCenter = new UdpClientByCenter(udplocalIp, '8080', globalThis.carInfo?.gpsAddress, globalThis.carInfo?.hintPort) | ||||
|     udpClient.bindUdp() | ||||
|     udpClient.onMessage((val)=>{ | ||||
|       console.log('valval',val) | ||||
|     udpClient.onMessage((val) => { | ||||
|       console.log('valval', val) | ||||
|     }) | ||||
|     globalThis.judgeUdpClient = udpClient; | ||||
|     return { | ||||
|       send(bytes){ | ||||
|         if(udpIndex > currentUdpIndex){ | ||||
|           udpClient.sendMsg({id:45,list:bytes,carNo:globalThis.carInfo.carNo,placeId:globalThis.carInfo.examinationRoomId}) | ||||
|       send(bytes) { | ||||
|         if (udpIndex > currentUdpIndex) { | ||||
|           udpClient.sendMsg({ | ||||
|             id: 45, | ||||
|             list: bytes, | ||||
|             carNo: globalThis.carInfo.carNo, | ||||
|             placeId: globalThis.carInfo.examinationRoomId | ||||
|           }) | ||||
|           currentUdpIndex = udpIndex | ||||
|         } | ||||
|       } | ||||
|  | ||||
| @ -15,19 +15,21 @@ | ||||
| 
 | ||||
| import socket from '@ohos.net.socket'; | ||||
| import { Array2Byte } from '../utils/tools' | ||||
| import {getChuankouFn} from '../../common/service/indexService' | ||||
| import { getChuankouFn } from '../../common/service/indexService' | ||||
| 
 | ||||
| const TAG = '[PLC.UdpClient]' | ||||
| import prompt from '@ohos.prompt' | ||||
| 
 | ||||
| import hilog from '@ohos.hilog'; | ||||
| 
 | ||||
| export default class UdpClient { | ||||
|   private localIp: string = '' | ||||
|   private localIpPort: string = '' | ||||
|   private oppositeIp: string = '' | ||||
|   private oppositeIpPort: string = '' | ||||
| 
 | ||||
|   private udp: any = null | ||||
|   private udp: socket.UDPSocket = null | ||||
| 
 | ||||
|   // private stashFn:StashFuncotion
 | ||||
| 
 | ||||
|   constructor(udplocalIp: string, udplocalIpPort: string, udpOppositeIp: string, udpOppositeIpPort: string) { | ||||
| @ -46,7 +48,7 @@ export default class UdpClient { | ||||
|     this.oppositeIp = oppositeIp | ||||
|     this.localIpPort = localIpPort | ||||
|     this.oppositeIpPort = oppositeIpPort | ||||
|     hilog.info(0x0000, 'udpCLient', 'rebind'+this.localIp+this.localIpPort); | ||||
|     hilog.info(0x0000, 'udpCLient', 'rebind' + this.localIp + this.localIpPort); | ||||
|     let promise = this.udp.bind({ | ||||
|       address: this.localIp, port: parseInt(this.localIpPort), family: 1 | ||||
|     }); | ||||
| @ -61,7 +63,7 @@ export default class UdpClient { | ||||
|   bindUdp() { | ||||
|     console.log('localIp', this.localIp) | ||||
|     console.log('localIpPort', this.localIpPort) | ||||
|     hilog.info(0x0000, 'udpCLient', 'bind'+ this.localIp+this.localIpPort); | ||||
|     hilog.info(0x0000, 'udpCLient', 'bind' + this.localIp + this.localIpPort); | ||||
| 
 | ||||
|     let promise = this.udp.bind({ | ||||
|       address: '192.168.7.170', port: 20122, family: 1 | ||||
| @ -75,9 +77,11 @@ export default class UdpClient { | ||||
|       console.log(`${TAG}udpCLient udp bind failed:${JSON.stringify(err)}`); | ||||
|     }); | ||||
|   } | ||||
|   setMsgCallBack(callback){ | ||||
| 
 | ||||
|   setMsgCallBack(callback) { | ||||
|     // this.stashFn=callback?callback:()=>{}
 | ||||
|   } | ||||
| 
 | ||||
|   sendMsg(msg) { | ||||
|     console.log('sendsnd01') | ||||
|     hilog.info(0x0000, 'udpCLient', 'send'); | ||||
| @ -101,18 +105,19 @@ export default class UdpClient { | ||||
|       console.log(`${TAG}udpCLient udp send fail:${JSON.stringify(err)}`); | ||||
|     }); | ||||
|   } | ||||
|   onError(callback?){ | ||||
|    this.udp.on('error',async err => { | ||||
|      console.log('udpdiushierroring') | ||||
|      hilog.info(0x0000, 'udpCLientonerror', 'error'+ JSON.stringify(err)); | ||||
|      console.log("on error, err:" + JSON.stringify(err)) | ||||
|      await this.bindUdp() | ||||
|      await this.sendMsg('111') | ||||
|      await this.onMessage(callback) | ||||
|      // callback&&callback()
 | ||||
|      // this.closeUdp(()=>{
 | ||||
|      //   this.bindUdp()
 | ||||
|      // })
 | ||||
| 
 | ||||
|   onError(callback?) { | ||||
|     this.udp.on('error', async err => { | ||||
|       console.log('udpdiushierroring') | ||||
|       hilog.info(0x0000, 'udpCLientonerror', 'error' + JSON.stringify(err)); | ||||
|       console.log("on error, err:" + JSON.stringify(err)) | ||||
|       await this.bindUdp() | ||||
|       await this.sendMsg('111') | ||||
|       await this.onMessage(callback) | ||||
|       // callback&&callback()
 | ||||
|       // this.closeUdp(()=>{
 | ||||
|       //   this.bindUdp()
 | ||||
|       // })
 | ||||
|     }); | ||||
|   } | ||||
| 
 | ||||
| @ -144,14 +149,14 @@ export default class UdpClient { | ||||
|         } | ||||
|         console.log(`${TAG} udp222 on message array buffer:${str}`); | ||||
| 
 | ||||
|         strachArr[28]=globalThis.chuankoMsg||'0' | ||||
|         strachArr[28] = globalThis.chuankoMsg || '0' | ||||
|         // this.stashFn(str)
 | ||||
|         const newArr=JSON.parse(JSON.stringify(strachArr)) | ||||
|         const newArr = JSON.parse(JSON.stringify(strachArr)) | ||||
|         // this.stashFn=()=>{}
 | ||||
|         callback&&callback(newArr.toString()) | ||||
|         callback && callback(newArr.toString()) | ||||
| 
 | ||||
|       } else { | ||||
|         callback&&callback('') | ||||
|         callback && callback('') | ||||
|       } | ||||
|       console.log('messageTimeEnd') | ||||
| 
 | ||||
| @ -183,41 +188,25 @@ export default class UdpClient { | ||||
|     }, 3000) | ||||
|   } | ||||
| 
 | ||||
|   closeUdp(callback) { | ||||
| 
 | ||||
|     this.udp.close(err => { | ||||
|       hilog.info(0x0000, 'udpCLient', 'close'); | ||||
| 
 | ||||
|       if (err) { | ||||
|         hilog.info(0x0000, 'udpCLient', 'closeonerror'); | ||||
| 
 | ||||
|       } else { | ||||
|         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');
 | ||||
|         // });
 | ||||
|       } | ||||
|     }); | ||||
| 
 | ||||
|   closeUdp() { | ||||
|     return new Promise<void>((resolve, reject) => { | ||||
|       this.udp.close().then(() => { | ||||
|         hilog.info(0x0000, 'udpClient', 'close'); | ||||
|         return this.udp.getState() | ||||
|       }).then((data) => { | ||||
|         if (!data.isClose) { | ||||
|           setTimeout(() => { | ||||
|             resolve() | ||||
|           }, 1000) | ||||
|         } | ||||
|       }).catch(err => { | ||||
|         hilog.error(0x0000, 'udpClient', err); | ||||
|         reject(err) | ||||
|       }) | ||||
|     }) | ||||
|   } | ||||
| } | ||||
| 
 | ||||
| interface StashFunction { | ||||
|   (str: string) | ||||
| } | ||||
| @ -17,8 +17,9 @@ import socket from '@ohos.net.socket'; | ||||
| import fs from '@ohos.file.fs' | ||||
| import mediaLibrary from '@ohos.multimedia.mediaLibrary' | ||||
| import FileUtil from '../../common/utils/File' | ||||
| import {fillZero,string2Bytes} from '../utils/tools' | ||||
| import { fillZero, string2Bytes } from '../utils/tools' | ||||
| import { GlobalConfig } from '../../config/index' | ||||
| 
 | ||||
| const TAG = '[UdpDemo.UdpClient]' | ||||
| // import common from '@ohos.app.ability.common';
 | ||||
| import hilog from '@ohos.hilog'; | ||||
| @ -27,216 +28,230 @@ import call from '@ohos.telephony.call'; | ||||
| 
 | ||||
| 
 | ||||
| export default class UdpClientByCenter { | ||||
|     private localIp: string = '' | ||||
|     private localIpPort: string = '' | ||||
|     private oppositeIp: string = '' | ||||
|     private oppositeIpPort: string = '' | ||||
|     private udpMsg: any='' | ||||
|     private num:number  = 0 | ||||
|     private fileUtil: FileUtil | ||||
|     private udp: any = null | ||||
|     private sendId: any = 0 | ||||
|     private lsh: string = null | ||||
|     private context | ||||
|     private stashFn:StashFunction | ||||
|     private headLenth:number=9 //消息头长度
 | ||||
|     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(); | ||||
|   private localIp: string = '' | ||||
|   private localIpPort: string = '' | ||||
|   private oppositeIp: string = '' | ||||
|   private oppositeIpPort: string = '' | ||||
|   private udpMsg: any = '' | ||||
|   private num: number = 0 | ||||
|   private fileUtil: FileUtil | ||||
|   private udp: any = null | ||||
|   private sendId: any = 0 | ||||
|   private lsh: string = null | ||||
|   private context | ||||
|   private stashFn: StashFunction | ||||
|   private headLenth: number = 9 | ||||
|   //消息头长度
 | ||||
|   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 = () => { | ||||
|     } | ||||
|     rebindUdp(localIp: string, localIpPort:string,oppositeIp: string,oppositeIpPort:string){ | ||||
|         this.localIp = localIp | ||||
|         this.oppositeIp = oppositeIp | ||||
|         this.localIpPort = localIpPort | ||||
|         this.oppositeIpPort = oppositeIpPort | ||||
|     this.udp = socket.constructUDPSocketInstance(); | ||||
|   } | ||||
| 
 | ||||
|         let promise = this.udp.bind({ | ||||
|             // address: '192.168.7.170', port: 20122, family: 1
 | ||||
|             address: this.localIp, port: parseInt(this.localIpPort), family: 1 | ||||
|         }); | ||||
|   rebindUdp(localIp: string, localIpPort: string, oppositeIp: string, oppositeIpPort: string) { | ||||
|     this.localIp = localIp | ||||
|     this.oppositeIp = oppositeIp | ||||
|     this.localIpPort = localIpPort | ||||
|     this.oppositeIpPort = oppositeIpPort | ||||
| 
 | ||||
|         promise.then(() => { | ||||
|             console.log(`${TAG} udp bind success`); | ||||
|         }).catch(err => { | ||||
|     let promise = this.udp.bind({ | ||||
|       // address: '192.168.7.170', port: 20122, family: 1
 | ||||
|       address: this.localIp, port: parseInt(this.localIpPort), family: 1 | ||||
|     }); | ||||
| 
 | ||||
|             console.log(`${TAG} udp bind failed:${JSON.stringify(err)}`); | ||||
|         }); | ||||
|     promise.then(() => { | ||||
|       console.log(`${TAG} udp bind success`); | ||||
|     }).catch(err => { | ||||
| 
 | ||||
|       console.log(`${TAG} udp bind failed:${JSON.stringify(err)}`); | ||||
|     }); | ||||
|   } | ||||
| 
 | ||||
|   initHeartSendMsg(param, context) { | ||||
|     this.initParam = param | ||||
|     this.context = context | ||||
|   } | ||||
| 
 | ||||
|   bindUdp() { | ||||
|     let promise = this.udp.bind({ | ||||
|       address: this.localIp, port: parseInt(this.localIpPort), family: 1 | ||||
|     }); | ||||
|     promise.then(() => { | ||||
|       console.log(`${TAG} udp bind success`); | ||||
|     }).catch(err => { | ||||
| 
 | ||||
|       console.log(`${TAG} udp bind failed:${JSON.stringify(err)}`); | ||||
|     }); | ||||
|   } | ||||
| 
 | ||||
|   //异或运算
 | ||||
|   setMessageExclusive(tmpList) { | ||||
|     let result = tmpList[0]; | ||||
|     for (let i = 1; i < tmpList.length; i++) { | ||||
|       result = result ^ tmpList[i] | ||||
|     } | ||||
|     initHeartSendMsg(param,context){ | ||||
|         this.initParam=param | ||||
|         this.context=context | ||||
|     } | ||||
|     bindUdp() { | ||||
|         let promise = this.udp.bind({ | ||||
|             address: this.localIp, port: parseInt(this.localIpPort), family: 1 | ||||
|         }); | ||||
|         promise.then(() => { | ||||
|             console.log(`${TAG} udp bind success`); | ||||
|         }).catch(err => { | ||||
|     return [result]; | ||||
|   } | ||||
| 
 | ||||
|             console.log(`${TAG} udp bind failed:${JSON.stringify(err)}`); | ||||
|         }); | ||||
|   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; | ||||
|   } | ||||
| 
 | ||||
|     //异或运算
 | ||||
|     setMessageExclusive(tmpList){ | ||||
|         let result = tmpList[0]; | ||||
|         for (let i = 1; i < tmpList.length; i++) { | ||||
|             result = result ^ tmpList[i] | ||||
|   //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); | ||||
|     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] | ||||
|     console.log('BitArray', arr) | ||||
|     return this.Array2Byte(arr).buffer | ||||
| 
 | ||||
|   } | ||||
| 
 | ||||
|   setMsgHead({id, list, placeId=62, carNo=489}) { | ||||
|     let a = string2Bytes(`${id}${fillZero(placeId, 3)}`, 2 * 8); | ||||
|     let b = string2Bytes(`${carNo}${this.lsh}`, 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('sendsnd1') | ||||
|     //udpOppositeIp
 | ||||
|     let promise = this.udp.send({ | ||||
|       data: msgData, | ||||
|       address: { | ||||
|         address: this.oppositeIp, | ||||
|         port: parseInt(this.oppositeIpPort), | ||||
|       } | ||||
|     }); | ||||
|     promise.then(() => { | ||||
|       console.log(`${TAG} udpLine send success:`); | ||||
|     }).catch(err => { | ||||
|       console.log(`${TAG} udpLine send fail:${JSON.stringify(err)}`); | ||||
|     }); | ||||
|   } | ||||
| 
 | ||||
|   setMsgCallBack(callback) { | ||||
|     this.stashFn = callback ? callback : () => { | ||||
|     } | ||||
|   } | ||||
| 
 | ||||
|   sendMsg(param, context?) { | ||||
|     console.log('paramparam', JSON.stringify(param)) | ||||
|     if (context) { | ||||
|       this.context = context | ||||
|     } | ||||
|     this.sendId = param.id | ||||
|     console.log('sendMsg', JSON.stringify(param)) | ||||
|     const msgData = this.setWholeMsg(param) | ||||
|     // const msgData=this.setMsyBody('31','010000000000000')
 | ||||
|     let promise = this.udp.send({ | ||||
|       data: msgData, | ||||
|       address: { | ||||
|         address: this.oppositeIp, | ||||
|         port: parseInt(this.oppositeIpPort), | ||||
|       } | ||||
|     }); | ||||
|     promise.then(() => { | ||||
|       if (param.sendCallback) { | ||||
|         param.sendCallback() | ||||
|       } | ||||
|       // if(this.sendId=='46'&¶m.callback){
 | ||||
|       //     param.callback()
 | ||||
|       // }
 | ||||
|       console.log(`${TAG} udp send success:`); | ||||
|     }).catch(err => { | ||||
|       console.log(`${TAG} udp send fail:${JSON.stringify(err)}`); | ||||
|     }); | ||||
|   } | ||||
| 
 | ||||
|   onMessage(callback, type?) { | ||||
|     this.udp.on('message', value => { | ||||
|       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) | ||||
|       hilog.info(0x0000, 'bitbit', JSON.stringify(arr)); | ||||
| 
 | ||||
|       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 | ||||
|       }) | ||||
|     }); | ||||
|   } | ||||
| 
 | ||||
|   onError(callback?) { | ||||
|     this.udp.on('error', err => { | ||||
|       console.log('udpbycenterdiushierroring') | ||||
|       hilog.info(0x0000, 'udpCLientBycenteronerror', 'error' + JSON.stringify(err)); | ||||
|       console.log("on error, err:" + JSON.stringify(err)) | ||||
|       // this.closeUdp(()=>{
 | ||||
|       //   this.bindUdp()
 | ||||
|       // })
 | ||||
|     }); | ||||
|   } | ||||
| 
 | ||||
|   closeUdp() { | ||||
|     return new Promise<void>((resolve, reject) => { | ||||
|       this.udp.close().then(() => { | ||||
|         hilog.info(0x0000, 'udpClient', 'close'); | ||||
|         return this.udp.getState() | ||||
|       }).then((data) => { | ||||
|         if (!data.isClose) { | ||||
|           setTimeout(() => { | ||||
|             resolve() | ||||
|           }, 1000) | ||||
|         } | ||||
|         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; | ||||
|     } | ||||
|     //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); | ||||
|         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] | ||||
|         console.log('BitArray',arr) | ||||
|         return this.Array2Byte(arr).buffer | ||||
| 
 | ||||
|     } | ||||
|     setMsgHead({id, list, placeId=62, carNo=489}){ | ||||
|         let a = string2Bytes(`${id}${fillZero(placeId,3)}`, 2*8); | ||||
|         let b = string2Bytes(`${carNo}${this.lsh}`, 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('sendsnd1') | ||||
|         //udpOppositeIp
 | ||||
|         let promise = this.udp.send({ | ||||
|             data: msgData, | ||||
|             address: { | ||||
|                 address: this.oppositeIp, | ||||
|                 port: parseInt(this.oppositeIpPort), | ||||
|             } | ||||
|         }); | ||||
|         promise.then(() => { | ||||
|             console.log(`${TAG} udpLine send success:`); | ||||
|         }).catch(err => { | ||||
|             console.log(`${TAG} udpLine send fail:${JSON.stringify(err)}`); | ||||
|         }); | ||||
|     } | ||||
|     setMsgCallBack(callback){ | ||||
|         this.stashFn=callback?callback:()=>{} | ||||
|     } | ||||
|     sendMsg(param,context?) { | ||||
|         console.log('paramparam',JSON.stringify(param)) | ||||
|         if(context){ | ||||
|             this.context=context | ||||
|         } | ||||
|         this.sendId=param.id | ||||
|         console.log('sendMsg',JSON.stringify(param)) | ||||
|         const msgData=this.setWholeMsg(param) | ||||
|         // const msgData=this.setMsyBody('31','010000000000000')
 | ||||
|         let promise = this.udp.send({ | ||||
|             data: msgData, | ||||
|             address: { | ||||
|                 address: this.oppositeIp, | ||||
|                 port: parseInt(this.oppositeIpPort), | ||||
|             } | ||||
|         }); | ||||
|         promise.then(() => { | ||||
|             if(param.sendCallback){ | ||||
|                 param.sendCallback() | ||||
|             } | ||||
|             // if(this.sendId=='46'&¶m.callback){
 | ||||
|             //     param.callback()
 | ||||
|             // }
 | ||||
|             console.log(`${TAG} udp send success:`); | ||||
|         }).catch(err => { | ||||
|             console.log(`${TAG} udp send fail:${JSON.stringify(err)}`); | ||||
|         }); | ||||
|     } | ||||
|     onMessage(callback,type?) { | ||||
|         this.udp.on('message', value => { | ||||
|             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) | ||||
|             hilog.info(0x0000, 'bitbit', JSON.stringify(arr)); | ||||
| 
 | ||||
|             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}) | ||||
|         }); | ||||
|     } | ||||
|     onError(callback?){ | ||||
|         this.udp.on('error', err => { | ||||
|             console.log('udpbycenterdiushierroring') | ||||
|             hilog.info(0x0000, 'udpCLientBycenteronerror', 'error'+ JSON.stringify(err)); | ||||
|             console.log("on error, err:" + JSON.stringify(err)) | ||||
|             // this.closeUdp(()=>{
 | ||||
|             //   this.bindUdp()
 | ||||
|             // })
 | ||||
|         }); | ||||
|     } | ||||
|     closeUdp(callback) { | ||||
|         this.udp.close(err=>{ | ||||
|             if(err){ | ||||
| 
 | ||||
|             }else{ | ||||
|                 this.udp.getState((err, data) => { | ||||
|                     if (err) { | ||||
|                         return; | ||||
|                     }else{ | ||||
|                         if(!data.isisClose){ | ||||
|                             setTimeout(()=>{ | ||||
|                                 callback() | ||||
|                             },1000) | ||||
|                         } | ||||
|                     } | ||||
|                 }) | ||||
|                 // let promise = this.udp.getState({});
 | ||||
|                 // promise.then(data => {
 | ||||
|                 //
 | ||||
|                 //     console.log('getState success:' + JSON.stringify(data));
 | ||||
|                 // }).catch(err => {
 | ||||
|                 //     callback()
 | ||||
|                 //     console.log('getState fail');
 | ||||
|                 // });
 | ||||
|             } | ||||
|         }); | ||||
| 
 | ||||
|     } | ||||
|       }).catch(err => { | ||||
|         hilog.error(0x0000, 'udpClient', err); | ||||
|         reject(err) | ||||
|       }) | ||||
|     }) | ||||
|   } | ||||
| } | ||||
| 
 | ||||
| interface StashFunction { | ||||
|     (params: { id: number; length: number; body: any[]; sendId: string }): void; | ||||
|   (params: { | ||||
|     id: number; | ||||
|     length: number; | ||||
|     body: any[]; | ||||
|     sendId: string | ||||
|   }): void; | ||||
| } | ||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user