235 lines
6.6 KiB
TypeScript
Raw Normal View History

2024-01-05 11:11:15 +08:00
import socket from '@ohos.net.socket';
2024-07-30 10:35:41 +08:00
import hilog from '@ohos.hilog';
2024-08-07 08:57:40 +08:00
import { getTCP } from './GlobalTcp';
2024-08-26 15:09:13 +08:00
import FileUtil from './File';
import { dateFormat } from './tools';
2025-04-07 16:18:11 +08:00
import Prompt from '@system.prompt';
2024-07-03 16:19:55 +08:00
const TAG = 'socketTag[TcpDemo.TcpClient]'
2024-01-05 11:11:15 +08:00
export default class TcpClient {
2024-07-30 10:35:41 +08:00
private localIp: string = ''
private localIpPort: string = ''
private oppositeIp: string = ''
private oppositeIpPort: string = ''
2024-08-10 14:00:18 +08:00
private num: number = 0//重连次数
2025-01-03 10:25:31 +08:00
private tcpSendNum: number = 0//重连次数
2024-11-18 15:16:42 +08:00
private folderPath
2024-07-30 10:35:41 +08:00
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();
2024-11-18 15:16:42 +08:00
this.initPath()
2024-07-30 10:35:41 +08:00
}
onError(callback?) {
this.tcp.on('error', err => {
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG} tcpOnerror ${JSON.stringify(err)}`,
// })
2025-01-02 17:53:34 +08:00
2024-12-24 16:43:59 +08:00
globalThis.getCloseTcp = true
2025-01-02 17:53:34 +08:00
console.log(TAG, 'getCloseTtcpOnerror', JSON.stringify(err))
2024-07-30 10:35:41 +08:00
setTimeout(async () => {
2024-08-07 08:57:40 +08:00
getTCP()
2024-07-30 10:35:41 +08:00
}, 2000)
// this.closeUdp(()=>{
// this.bindUdp()
// })
});
}
bindTcp() {
2024-11-18 15:16:42 +08:00
this.writeLog({
time:dateFormat(new Date()),
message: `${TAG} tcpbind localIp${this.localIp} ${this.localIpPort}`,
})
2024-07-30 10:35:41 +08:00
return new Promise((resolve, reject) => {
let promise = this.tcp.bind({
address: this.localIp, port: parseInt(this.localIpPort), family: 1
}, err => {
if (err) {
2024-11-18 15:16:42 +08:00
this.writeLog({
time:dateFormat(new Date()),
message: `${TAG} tcpbind error ${JSON.stringify(err)}`,
})
2024-12-24 16:43:59 +08:00
setTimeout(async () => {
getTCP()
}, 2000)
2025-01-02 17:53:34 +08:00
console.log('getCloseTBinderror');
2024-07-30 10:35:41 +08:00
hilog.info(0x0000, 'testTag', "tcpBinderror:" + JSON.stringify(err));
resolve(true)
return
}
2025-01-02 17:53:34 +08:00
// console.log('testTag tcp bind success');
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG} testTag tcp bind success`,
// })
2024-07-30 10:35:41 +08:00
resolve(false)
})
})
}
connectTcp() {
2024-11-18 15:16:42 +08:00
this.writeLog({
time:dateFormat(new Date()),
message: `${TAG} tcpConnect oppositeIp ${ this.oppositeIp} ${this.oppositeIpPort}`,
})
2024-07-30 10:35:41 +08:00
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) {
2025-01-02 17:53:34 +08:00
console.log('getCloseTconnectsuccess','error',globalThis.getCloseTcp)
2024-11-18 15:16:42 +08:00
this.writeLog({
time:dateFormat(new Date()),
message: `${TAG} TCPconnect error ${JSON.stringify(err)}`,
})
2024-08-14 17:26:27 +08:00
setTimeout(() => {
getTCP()
resolve(false)
2024-12-24 16:43:59 +08:00
}, 9000)
2024-07-30 10:35:41 +08:00
return;
}
2024-01-05 11:11:15 +08:00
});
2025-01-02 17:53:34 +08:00
2024-07-30 10:35:41 +08:00
globalThis.getCloseTcp = false
resolve(true)
}).catch(err => {
2024-11-18 15:16:42 +08:00
console.log('socketTag','error')
this.writeLog({
time:dateFormat(new Date()),
message: `${TAG} TCPconnect error2 ${JSON.stringify(err)}`,
})
2024-12-20 13:28:03 +08:00
// globalThis.getCloseTcp = true
2024-12-24 16:43:59 +08:00
2024-07-30 10:35:41 +08:00
setTimeout(() => {
2024-08-10 14:00:18 +08:00
getTCP()
2024-07-30 10:35:41 +08:00
resolve(false)
2024-12-24 16:43:59 +08:00
}, 9000)
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG} tcp connect error`,
// })
2024-07-30 10:35:41 +08:00
});
})
}
sendMsg(msg: string) {
return new Promise((reslove, reject) => {
let promise = this.tcp.send({
data: msg
});
promise.then(() => {
reslove(true)
}).catch(err => {
2025-01-03 10:25:31 +08:00
this.tcpSendNum++
if(!globalThis.getCloseTcp&&this.tcpSendNum>10){
2025-01-02 17:53:34 +08:00
setTimeout(async () => {
getTCP(true)
}, 3000)
2025-01-03 10:25:31 +08:00
this.tcpSendNum=0
2025-01-02 17:53:34 +08:00
return
}
2024-12-24 16:43:59 +08:00
console.log(`${TAG} TCPsend error ${JSON.stringify(err)}`)
// this.writeLog({
// time:dateFormat(new Date()),
// message: `${TAG} TCPsend error ${JSON.stringify(err)}`,
// })
2025-06-25 10:19:26 +08:00
reject(false)
2024-07-30 10:35:41 +08:00
});
})
}
onMessage(callback?) {
this.tcp.on('message', value => {
2024-08-26 19:27:23 +08:00
// this.writeLog({
// time:dateFormat(new Date()),
// PLC:`${TAG} Tcponmessage`,
// })
2025-06-25 10:19:26 +08:00
globalThis.tcpStep=0
2024-08-14 13:15:03 +08:00
globalThis.tcpUdpError = false
2024-07-30 10:35:41 +08:00
if (value) {
callback && callback(value.message)
2024-07-30 10:35:41 +08:00
} else {
callback && callback('')
}
2024-08-14 14:46:33 +08:00
clearInterval(globalThis.intervaltcp)
globalThis.intervaltcp=setInterval(()=>{
2024-11-18 15:16:42 +08:00
//程序断开
if (globalThis.tcpUdpError) {
console.log(TAG,'tcp信号丢失')
2024-12-20 13:28:03 +08:00
// getTCP()
2025-04-07 16:18:11 +08:00
Prompt.showToast({
2024-11-18 15:16:42 +08:00
message: 'tcp信号丢失',
duration: 2000
});
}
2025-03-24 08:57:29 +08:00
2024-11-18 15:16:42 +08:00
globalThis.tcpUdpError = true;
2024-08-14 14:46:33 +08:00
},3000)
2024-07-30 10:35:41 +08:00
// callback(value.message)
});
}
2024-11-18 15:16:42 +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-11-18 15:16:42 +08:00
}
async initPath(){
2024-12-29 21:43:12 +08:00
return
2024-11-18 15:16:42 +08:00
const fileUtil = new FileUtil(globalThis.context)
const date=dateFormat(new Date).split(' ')[0]
this.folderPath = await fileUtil.initFolder(`/PLC/${date}`);
2024-08-26 15:09:13 +08:00
}
2024-07-30 10:35:41 +08:00
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
2024-11-18 15:16:42 +08:00
this.writeLog({
time:dateFormat(new Date()),
message: `${TAG} tcp closeSuccess`,
})
2025-01-02 17:53:34 +08:00
console.log('getCloseTcpsocketTagclose','success',globalThis.getCloseTcp)
2024-07-30 10:35:41 +08:00
console.log(TAG, 'tcpCloseSuccess')
callback()
reslove(true)
}).catch(err => {
2024-12-24 16:43:59 +08:00
setTimeout(async () => {
getTCP(true)
}, 9000)
2024-11-18 15:16:42 +08:00
this.writeLog({
time:dateFormat(new Date()),
message: `${TAG} tcpclose error ${JSON.stringify(err)}`,
})
2025-01-02 17:53:34 +08:00
console.log('getCloseTcpsocketTagclose','error',globalThis.getCloseTcp)
2024-07-30 10:35:41 +08:00
reslove(false)
});
})
}
2024-01-05 11:11:15 +08:00
}