import socket from '@ohos.net.socket'; import hilog from '@ohos.hilog'; import { getTCP } from './GlobalTcp'; import prompt from '@ohos.prompt'; import FileUtil from './File'; import { dateFormat } from './tools'; 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 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 this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcponerror localIp${JSON.stringify(err)}`, }) console.log(TAG, 'tcpOnerror', JSON.stringify(err)) setTimeout(async () => { getTCP() }, 2000) // this.closeUdp(()=>{ // this.bindUdp() // }) }); } rebindTcp(localIp: string, localIpPort: string, oppositeIp: string, oppositeIpPort: string) { return new Promise((resolve, reject) => { this.localIp = localIp this.oppositeIp = oppositeIp this.localIpPort = localIpPort this.oppositeIpPort = oppositeIpPort console.log(TAG, 'tcpreBind', this.localIp, this.localIpPort) 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} tcprebind tcpreBinderror${JSON.stringify(err)}`, }) setTimeout(async () => { getTCP() }, 2000) // globalThis.getCloseTcp = true hilog.info(0x0000, 'testTag', "tcpreBinderror:" + JSON.stringify(err)); resolve(true) } this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcprebind success`, }) console.log('testTag,rebindtestTag tcp bind success'); // globalThis.getCloseTcp = false resolve(false) }) }) // 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 // }); } bindTcp() { this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcpbind localIp${this.localIp} ${this.localIpPort}`, }) console.log(TAG, 'tcpbind', this.localIp, '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()), // PLC:`${TAG} testTag tcp bind faile ${JSON.stringify(err)}`, // }) this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcpbind error ${JSON.stringify(err)}`, }) setTimeout(async () => { getTCP() }, 2000) console.log('testTag tcp bind faile'); 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) }) }) console.log('localIp', this.localIp) console.log('localIpPort', 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 // }); } connectTcp() { this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcpConnect oppositeIp ${ this.oppositeIp} ${this.oppositeIpPort}`, }) console.log(TAG, 'tcpConnect', this.oppositeIp, 'localIp', 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(() => { console.log('testTagtestTag000',) this.tcp.setExtraOptions({ keepAlive: true, }, err => { if (err) { this.writeLog({ time:dateFormat(new Date()), message: `${TAG} TCPconnect error ${JSON.stringify(err)}`, }) // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG} tcp connect rebind success`, // }) setTimeout(() => { this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcp重连`, }) getTCP() resolve(false) }, 9000) return; } }); console.log('socketTag','success') 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) { console.log(TAG, 'tcpSend', msg.length, msg) return new Promise((reslove, reject) => { let promise = this.tcp.send({ data: msg }); promise.then(() => { reslove(true) }).catch(err => { console.log(`${TAG} TCPsend error ${JSON.stringify(err)}`) // this.writeLog({ // time:dateFormat(new Date()), // message: `${TAG} TCPsend error ${JSON.stringify(err)}`, // }) reslove(false) }); }) } onMessage(callback?) { this.tcp.on('message', value => { // this.writeLog({ // time:dateFormat(new Date()), // PLC:`${TAG} Tcponmessage`, // }) console.log(TAG, 'Tcponmessage', value) globalThis.tcpUdpError = false // console.log('messageLengt',,value.message.length)) console.log('testTagtcpmsg') // console.log("on message, message:" + value.message+ ", remoteInfo:" ) if (value) { let dataView = new DataView(value.message) // const Arraybuffer=buffer.from(value.message, 5, dataView?.byteLength); const Arraybuffer = value.message.slice(5, dataView?.byteLength); callback && callback(Arraybuffer) } else { callback && callback('') } clearInterval(globalThis.intervaltcp) globalThis.intervaltcp=setInterval(()=>{ //程序断开 if (globalThis.tcpUdpError) { console.log(TAG,'tcp信号丢失') // getTCP() prompt.showToast({ message: 'tcp信号丢失', duration: 2000 }); } this.writeLog({ time:dateFormat(new Date()), message: `${TAG} tcp信号丢失`, }) 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(){ 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(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)}`, }) reslove(false) }); }) } }