import socket from '@ohos.net.socket'; import hilog from '@ohos.hilog'; import { getTCP } from './GlobalTcp'; import FileUtil from './File'; import { dateFormat } from './tools'; import Prompt from '@system.prompt'; const TAG = 'socketTag[TcpDemo.TcpClient]' export default class TcpClient { private localIp: string = '' private localIpPort: string = '' private oppositeIp: string = '' private oppositeIpPort: string = '' private num: number = 0//重连次数 private tcpSendNum: number = 0//重连次数 private folderPath private tcp: any = null constructor(tcplocalIp: string, tcplocalIpPort: string, tcpOppositeIp: string, tcpOppositePort: string) { this.localIp = tcplocalIp this.oppositeIp = tcpOppositeIp this.localIpPort = tcplocalIpPort this.oppositeIpPort = tcpOppositePort console.log(TAG, 'new Tcp', this.localIp, this.localIpPort, this.oppositeIp, this.oppositeIpPort) this.tcp = socket.constructTCPSocketInstance(); this.initPath() } onError(callback?) { this.tcp.on('error', err => { // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG} tcpOnerror ${JSON.stringify(err)}`, // }) globalThis.getCloseTcp = true console.log(TAG, 'getCloseTtcpOnerror', JSON.stringify(err)) setTimeout(async () => { getTCP() }, 2000) // this.closeUdp(()=>{ // this.bindUdp() // }) }); } bindTcp() { this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcpbind localIp${this.localIp} ${this.localIpPort}`, }) return new Promise((resolve, reject) => { let promise = this.tcp.bind({ address: this.localIp, port: parseInt(this.localIpPort), family: 1 }, err => { if (err) { this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcpbind error ${JSON.stringify(err)}`, }) setTimeout(async () => { getTCP() }, 2000) console.log('getCloseTBinderror'); hilog.info(0x0000, 'testTag', "tcpBinderror:" + JSON.stringify(err)); resolve(true) return } // console.log('testTag tcp bind success'); // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG} testTag tcp bind success`, // }) resolve(false) }) }) } connectTcp() { this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcpConnect oppositeIp ${ this.oppositeIp} ${this.oppositeIpPort}`, }) return new Promise((resolve, reject) => { let promise = this.tcp.connect({ address: { address: this.oppositeIp, port: parseInt(this.oppositeIpPort), family: 1 }, timeout: 6000 }); promise.then(() => { this.tcp.setExtraOptions({ keepAlive: true, }, err => { if (err) { console.log('getCloseTconnectsuccess','error',globalThis.getCloseTcp) this.writeLog({ time:dateFormat(new Date()), message: `${TAG} TCPconnect error ${JSON.stringify(err)}`, }) setTimeout(() => { getTCP() resolve(false) }, 9000) return; } }); globalThis.getCloseTcp = false resolve(true) }).catch(err => { console.log('socketTag','error') this.writeLog({ time:dateFormat(new Date()), message: `${TAG} TCPconnect error2 ${JSON.stringify(err)}`, }) // globalThis.getCloseTcp = true setTimeout(() => { getTCP() resolve(false) }, 9000) // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG} tcp connect error`, // }) }); }) } sendMsg(msg: string) { return new Promise((reslove, reject) => { let promise = this.tcp.send({ data: msg }); promise.then(() => { reslove(true) }).catch(err => { this.tcpSendNum++ if(!globalThis.getCloseTcp&&this.tcpSendNum>10){ setTimeout(async () => { getTCP(true) }, 3000) this.tcpSendNum=0 return } console.log(`${TAG} TCPsend error ${JSON.stringify(err)}`) // this.writeLog({ // time:dateFormat(new Date()), // message: `${TAG} TCPsend error ${JSON.stringify(err)}`, // }) reject(false) }); }) } onMessage(callback?) { this.tcp.on('message', value => { // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG} Tcponmessage`, // }) globalThis.tcpStep=0 globalThis.tcpUdpError = false if (value) { callback && callback(value.message) } else { callback && callback('') } clearInterval(globalThis.intervaltcp) globalThis.intervaltcp=setInterval(()=>{ //程序断开 if (globalThis.tcpUdpError) { console.log(TAG,'tcp信号丢失') // getTCP() Prompt.showToast({ message: 'tcp信号丢失', duration: 2000 }); } globalThis.tcpUdpError = true; },3000) // callback(value.message) }); } async writeLog(param){ // const fileUtil = new FileUtil(globalThis.context) // fileUtil.editFile(`${this.folderPath}/plcLog.txt`, JSON.stringify(param)+`\n`) } async initPath(){ return const fileUtil = new FileUtil(globalThis.context) const date=dateFormat(new Date).split(' ')[0] this.folderPath = await fileUtil.initFolder(`/PLC/${date}`); } offTcp(callback) { console.log(TAG, 'tcpofff') this.tcp.off('testTagofmessg', callback); } closeTcp(callback) { return new Promise((reslove, reject) => { console.log(TAG, 'tcpClose') let promise = this.tcp.close(); promise.then(() => { globalThis.getCloseTcp = true this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcp closeSuccess`, }) console.log('getCloseTcpsocketTagclose','success',globalThis.getCloseTcp) console.log(TAG, 'tcpCloseSuccess') callback() reslove(true) }).catch(err => { setTimeout(async () => { getTCP(true) }, 9000) this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcpclose error ${JSON.stringify(err)}`, }) console.log('getCloseTcpsocketTagclose','error',globalThis.getCloseTcp) reslove(false) }); }) } }