refactor: 重构网络配置相关接口,优化文件处理逻辑
This commit is contained in:
parent
af338af32a
commit
94cf59b607
@ -1,196 +0,0 @@
|
|||||||
import socket from '@ohos.net.socket';
|
|
||||||
import util from '@ohos.util';
|
|
||||||
|
|
||||||
|
|
||||||
interface RequestKey {
|
|
||||||
time: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface RequestCallback {
|
|
||||||
url: string
|
|
||||||
type: number
|
|
||||||
resolve: Function
|
|
||||||
reject: Function
|
|
||||||
timeout: number
|
|
||||||
}
|
|
||||||
|
|
||||||
interface RequestParams {
|
|
||||||
method: string
|
|
||||||
data: object
|
|
||||||
type: 0 | 1
|
|
||||||
contentType: string
|
|
||||||
timeout: number
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Response {
|
|
||||||
serialNumber: string
|
|
||||||
data: string
|
|
||||||
isForwordHttp: string
|
|
||||||
}
|
|
||||||
|
|
||||||
let tag = "tcp request"
|
|
||||||
|
|
||||||
class TcpUtils {
|
|
||||||
private static instance: TcpUtils
|
|
||||||
private socket: socket.TCPSocket = socket.constructTCPSocketInstance()
|
|
||||||
private requestMap: Map<string, RequestCallback> = new Map<string, RequestCallback>()
|
|
||||||
private tick: number
|
|
||||||
private heartbeat: number
|
|
||||||
private cache: string = ''
|
|
||||||
private fileUtil = new FileUtil(AppStorage.get('context'))
|
|
||||||
private path = ""
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
if (!TcpUtils.instance) {
|
|
||||||
TcpUtils.instance = this
|
|
||||||
}
|
|
||||||
return TcpUtils.instance
|
|
||||||
}
|
|
||||||
|
|
||||||
async init() {
|
|
||||||
this.path = await this.fileUtil.initFolder('/config/tcpRequest')
|
|
||||||
this.socket.on("message", (res) => {
|
|
||||||
let decoder = util.TextDecoder.create()
|
|
||||||
let message = decoder.decodeWithStream(new Uint8Array(res.message))
|
|
||||||
console.log(tag, "on message", message)
|
|
||||||
this.cache += message
|
|
||||||
let start = this.cache.indexOf("^#")
|
|
||||||
let end = this.cache.indexOf("#$")
|
|
||||||
try {
|
|
||||||
if (start !== -1 && end !== -1) {
|
|
||||||
let message = this.cache.slice(start + 2, end)
|
|
||||||
this.cache = this.cache.slice(end + 2)
|
|
||||||
let tempIndex = message.indexOf("^#")
|
|
||||||
while (tempIndex > -1) {
|
|
||||||
message = message.slice(tempIndex + 2)
|
|
||||||
tempIndex = message.indexOf("^#")
|
|
||||||
}
|
|
||||||
let result: Response = JSON.parse(message)
|
|
||||||
let key = result.serialNumber
|
|
||||||
let data = result.data
|
|
||||||
let isSuccess = result.isForwordHttp === "1"
|
|
||||||
console.log(tag, "complete message")
|
|
||||||
let item = this.requestMap.get(key)
|
|
||||||
console.log(tag, "============", item?.url)
|
|
||||||
if (this.requestMap.get(key)?.type === 0) {
|
|
||||||
console.log(tag, "resolve message")
|
|
||||||
if (isSuccess) {
|
|
||||||
item?.resolve(JSON.parse(data))
|
|
||||||
} else {
|
|
||||||
item?.reject({
|
|
||||||
code: -1,
|
|
||||||
message: data || "request failed"
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.log(tag, "resolve message")
|
|
||||||
if (isSuccess) {
|
|
||||||
item?.resolve(data)
|
|
||||||
} else {
|
|
||||||
item?.reject({
|
|
||||||
code: -1,
|
|
||||||
message: data || "request failed"
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.requestMap.delete(key)
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.log(tag, "解析相应失败", JSON.stringify(e))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
this.loop()
|
|
||||||
return this.socket.connect({
|
|
||||||
address: { address: "172.37.55.191", port: 19998 }
|
|
||||||
}).then(() => {
|
|
||||||
this.heartbeat = setInterval(() => {
|
|
||||||
this.send("heart", JSON.stringify({
|
|
||||||
isHeartBeat: 1
|
|
||||||
}), false)
|
|
||||||
}, 1000 * 6)
|
|
||||||
console.log(tag, "connect success")
|
|
||||||
}).catch(err => {
|
|
||||||
console.log(tag, JSON.stringify(err))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
request(url: string, option: RequestParams, resolve, reject) {
|
|
||||||
let key = new Date().getTime()
|
|
||||||
this.requestMap.set(key + "", {
|
|
||||||
url,
|
|
||||||
resolve,
|
|
||||||
reject,
|
|
||||||
timeout: option.timeout,
|
|
||||||
type: option.type,
|
|
||||||
})
|
|
||||||
|
|
||||||
let message = {
|
|
||||||
url,
|
|
||||||
serialNumber: key,
|
|
||||||
type: option.type,
|
|
||||||
method: option.method,
|
|
||||||
data: option.data,
|
|
||||||
contentType: option.contentType,
|
|
||||||
isHeartBeat: "0",
|
|
||||||
}
|
|
||||||
|
|
||||||
this.send(key + "", JSON.stringify(message))
|
|
||||||
}
|
|
||||||
|
|
||||||
destroy() {
|
|
||||||
clearInterval(this.tick)
|
|
||||||
clearInterval(this.heartbeat)
|
|
||||||
}
|
|
||||||
|
|
||||||
private loop() {
|
|
||||||
this.tick = setInterval(() => {
|
|
||||||
let now = new Date().getTime()
|
|
||||||
this.requestMap.forEach((value, key) => {
|
|
||||||
if (now - Number(key) >= value.timeout) {
|
|
||||||
console.log("tcp request timeout url: ", value.url)
|
|
||||||
console.log("tcp request timeout key: ", key)
|
|
||||||
value.reject({
|
|
||||||
message: "tcp request timeout",
|
|
||||||
code: 2300028
|
|
||||||
})
|
|
||||||
this.requestMap.delete(key)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}, 100)
|
|
||||||
}
|
|
||||||
|
|
||||||
private async send(key: string, message: string, log: boolean = true) {
|
|
||||||
if (log) {
|
|
||||||
console.log(tag, 'send', message)
|
|
||||||
}
|
|
||||||
this.fileUtil.addFile(this.path + 'temp.txt', `^#${message}#$`)
|
|
||||||
this.socket.send({
|
|
||||||
data: `^#${message}#$`
|
|
||||||
}).then(() => {
|
|
||||||
if (log) {
|
|
||||||
console.log(tag, 'send success')
|
|
||||||
}
|
|
||||||
}).catch(async err => {
|
|
||||||
if (key !== "heart") {
|
|
||||||
console.log("tcp request send failed", this.requestMap.get(key).url)
|
|
||||||
this.requestMap.get(key).reject({
|
|
||||||
message: "tcp request send failed",
|
|
||||||
code: 2300007
|
|
||||||
})
|
|
||||||
}
|
|
||||||
await this.socket.close()
|
|
||||||
this.socket = socket.constructTCPSocketInstance()
|
|
||||||
await this.socket.connect({
|
|
||||||
address: { address: "172.37.55.191", port: 19998 }
|
|
||||||
}).then(res => {
|
|
||||||
console.log("tcp request reconnect success", JSON.stringify(res))
|
|
||||||
}).catch(err => {
|
|
||||||
console.log("tcp request reconnect failed", JSON.stringify(err))
|
|
||||||
})
|
|
||||||
console.log(tag, JSON.stringify(err))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const tcpUtil = new TcpUtils()
|
|
||||||
@ -1,37 +0,0 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2023 Hunan OpenValley Digital Industry Development 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.
|
|
||||||
*/
|
|
||||||
|
|
||||||
const TEN = 10; // 这是数字10
|
|
||||||
const SIXTY = 60; // 时间进制
|
|
||||||
const THOUSAND = 1000; // 这是数字1000
|
|
||||||
|
|
||||||
export function tempNum(num: number): string {
|
|
||||||
if (num < TEN) {
|
|
||||||
return '0' + num;
|
|
||||||
}
|
|
||||||
return num.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getDurationString(duration: number): string {
|
|
||||||
let hour = Math.floor(duration / (THOUSAND * SIXTY * SIXTY));
|
|
||||||
let minute = Math.floor((duration - hour * (THOUSAND * SIXTY * SIXTY)) / (THOUSAND * SIXTY));
|
|
||||||
let second = Math.floor(
|
|
||||||
(duration - hour * (THOUSAND * SIXTY * SIXTY) - minute * (SIXTY * THOUSAND)) / THOUSAND
|
|
||||||
);
|
|
||||||
if (hour > 0) {
|
|
||||||
return `${tempNum(hour)}:${tempNum(minute)}:${tempNum(second)}`;
|
|
||||||
}
|
|
||||||
return `${tempNum(minute)}:${tempNum(second)}`;
|
|
||||||
}
|
|
||||||
@ -1,16 +1,14 @@
|
|||||||
import UIAbility from '@ohos.app.ability.UIAbility';
|
import UIAbility from '@ohos.app.ability.UIAbility';
|
||||||
import hilog from '@ohos.hilog';
|
import hilog from '@ohos.hilog';
|
||||||
import window from '@ohos.window';
|
import window from '@ohos.window';
|
||||||
import relationalStore from '@ohos.data.relationalStore'
|
import { GlobalConfig } from '../config/global';
|
||||||
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
|
|
||||||
import { GlobalConfig } from '../config/global'
|
|
||||||
import { tcpUtil } from '../common/utils/TcpRequest';
|
|
||||||
import { initTable } from '../common/service/initable';
|
import { initTable } from '../common/service/initable';
|
||||||
import { centerUDPClient, lightUDPClient, objUDPClient } from '../utils/UdpUtils';
|
import { centerUDPClient, lightUDPClient, objUDPClient } from '../utils/UdpUtils';
|
||||||
import Want from '@ohos.app.ability.Want';
|
import Want from '@ohos.app.ability.Want';
|
||||||
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
|
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
|
||||||
import { BaseInfoType, CarInfoType, ExaminerInfoType } from '../model';
|
import { BaseInfoType, CarInfoType, ExaminerInfoType } from '../model';
|
||||||
import DB from '../utils/DbSql';
|
import DB from '../utils/DbSql';
|
||||||
|
import { tcpUtil } from '../utils/TcpRequest';
|
||||||
|
|
||||||
export default class EntryAbility extends UIAbility {
|
export default class EntryAbility extends UIAbility {
|
||||||
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
|
async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
|
||||||
|
|||||||
@ -114,4 +114,22 @@ export interface CarInfoType {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
// TODO
|
||||||
export interface ExaminerInfoType {}
|
export interface ExaminerInfoType {}
|
||||||
|
|
||||||
|
// 一些运行配置
|
||||||
|
export interface EnvironmentConfigurationType {
|
||||||
|
udplocalIp?: string,
|
||||||
|
udplocalIpPort?: string,
|
||||||
|
udpOppositeIp?: string,
|
||||||
|
udpOppositeIpPort?: string,
|
||||||
|
tcplocalIp?: string,
|
||||||
|
tcplocalIpPort?: string,
|
||||||
|
tcpOppositeIp?: string,
|
||||||
|
tcpOppositePort?: string,
|
||||||
|
netMask?: string,
|
||||||
|
gateway?: string,
|
||||||
|
dnsServers?: string,
|
||||||
|
centerIp?: string,
|
||||||
|
centerPort?: string,
|
||||||
|
terType?: string
|
||||||
|
}
|
||||||
@ -1,15 +0,0 @@
|
|||||||
export interface NetworkConfigType {
|
|
||||||
udplocalIp: string;
|
|
||||||
udplocalIpPort: string;
|
|
||||||
udpOppositeIp: string;
|
|
||||||
udpOppositeIpPort: string;
|
|
||||||
tcplocalIp: string;
|
|
||||||
tcplocalIpPort: string;
|
|
||||||
tcpOppositeIp: string;
|
|
||||||
tcpOppositePort: string;
|
|
||||||
netMask: string;
|
|
||||||
gateway: string;
|
|
||||||
dnsServers: string;
|
|
||||||
centerIp: string;
|
|
||||||
centerPort: string;
|
|
||||||
}
|
|
||||||
@ -3,9 +3,9 @@ import ethernet from '@ohos.net.ethernet';
|
|||||||
|
|
||||||
import common from '@ohos.app.ability.common';
|
import common from '@ohos.app.ability.common';
|
||||||
import { GlobalConfig } from '../config';
|
import { GlobalConfig } from '../config';
|
||||||
import { NetworkConfigType } from '../model/TerminalInfos';
|
|
||||||
import Prompt from '@system.prompt';
|
import Prompt from '@system.prompt';
|
||||||
import FileUtils from '../utils/FileUtils';
|
import FileUtils from '../utils/FileUtils';
|
||||||
|
import { EnvironmentConfigurationType } from '../model/Common';
|
||||||
|
|
||||||
|
|
||||||
@Entry
|
@Entry
|
||||||
@ -17,20 +17,20 @@ struct Index {
|
|||||||
// @State textList2: string[] = []
|
// @State textList2: string[] = []
|
||||||
@State ratio: number = 1700 / 960
|
@State ratio: number = 1700 / 960
|
||||||
@State inputFontSize: number = 12 //12
|
@State inputFontSize: number = 12 //12
|
||||||
//
|
|
||||||
// @State inputTextList1: string[] = ['192.168.7.170','8084','192.168.7.170','20122','255.255.255.0','192.168.7.1','','','114.114.114.114','112.80.35.83','11055' +
|
|
||||||
// '',]
|
|
||||||
// @State inputTextList2: string[] = ['192.168.7.124','20022']
|
|
||||||
|
|
||||||
// @State inputTextList1: string[] = ['172.37.55.191','18782','192.168.7.1','8082','255.255.255.0','192.168.7.170','114.114.114.114','192.168.7.124','20022','172.37.55.59','20122']
|
// @State inputTextList1: string[] = ['172.37.55.191','18782','192.168.7.1','8082','255.255.255.0','192.168.7.170','114.114.114.114','192.168.7.124','20022','172.37.55.59','20122']
|
||||||
@State inputTextList1: string[] =
|
@State inputTextList1: string[] =
|
||||||
['172.37.55.191', '18782', '172.37.55.191', '8082', '255.255.255.0', '192.168.7.1', '114.114.114.114',
|
['172.37.55.191', '18782', '172.37.55.191', '8082', '255.255.255.0', '192.168.7.1', '114.114.114.114',
|
||||||
'192.168.7.124', '20022', '192.168.7.170', '20122']
|
'192.168.7.124', '20022', '192.168.7.170', '20122']
|
||||||
// @State inputTextList2: string[] = []
|
//
|
||||||
// 112.80.35.83 11052
|
// @State inputTextList1: string[] = ['192.168.7.170','8084','192.168.7.170','20122','255.255.255.0','192.168.7.1','','','114.114.114.114','112.80.35.83','11055' +
|
||||||
|
// '',]
|
||||||
|
// @State inputTextList2: string[] = ['192.168.7.124','20022']
|
||||||
// @State inputTextList1: string[] = ['192.168.36.2','8084','192.168.36.200','20122','255.255.255.0','192.168.36.1','','','114.114.114.114','192.168.36.139','8000']
|
// @State inputTextList1: string[] = ['192.168.36.2','8084','192.168.36.200','20122','255.255.255.0','192.168.36.1','','','114.114.114.114','192.168.36.139','8000']
|
||||||
@State @Watch('outClick') outFlag: boolean = false;
|
@State @Watch('outClick') outFlag: boolean = false;
|
||||||
|
// @State inputTextList2: string[] = []
|
||||||
|
// 112.80.35.83 11052
|
||||||
scroller: Scroller = new Scroller()
|
scroller: Scroller = new Scroller()
|
||||||
|
private fileUtil: FileUtils
|
||||||
// @State inputTextList2: string[] = ['192.168.36.139','20022']
|
// @State inputTextList2: string[] = ['192.168.36.139','20022']
|
||||||
private context = getContext(this) as common.UIAbilityContext;
|
private context = getContext(this) as common.UIAbilityContext;
|
||||||
|
|
||||||
@ -85,9 +85,8 @@ struct Index {
|
|||||||
|
|
||||||
Column() {
|
Column() {
|
||||||
Image($r('app.media.terminal_save')).width('20.5%').height('74%').onClick(async () => {
|
Image($r('app.media.terminal_save')).width('20.5%').height('74%').onClick(async () => {
|
||||||
const fileUtil = new FileUtils(this.context)
|
const folderPath = await this.fileUtil.initFolder(`/config`);
|
||||||
const folderPath = await fileUtil.initFolder(`/config`);
|
const param: EnvironmentConfigurationType = {
|
||||||
const param: NetworkConfigType = {
|
|
||||||
udplocalIp: this.inputTextList1[9],
|
udplocalIp: this.inputTextList1[9],
|
||||||
udplocalIpPort: this.inputTextList1[10],
|
udplocalIpPort: this.inputTextList1[10],
|
||||||
udpOppositeIp: this.inputTextList1[7],
|
udpOppositeIp: this.inputTextList1[7],
|
||||||
@ -102,7 +101,8 @@ struct Index {
|
|||||||
centerIp: this.inputTextList1[2],
|
centerIp: this.inputTextList1[2],
|
||||||
centerPort: this.inputTextList1[3]
|
centerPort: this.inputTextList1[3]
|
||||||
}
|
}
|
||||||
fileUtil.addFile(`${folderPath}/ipConfig.txt`, JSON.stringify(param), '')
|
this.fileUtil.addFile(`${folderPath}/ipConfig.txt`, JSON.stringify(param))
|
||||||
|
AppStorage.setOrCreate<EnvironmentConfigurationType>("EnvironmentConfiguration", param)
|
||||||
// upDateTableByArray('IpConfigTable',[])
|
// upDateTableByArray('IpConfigTable',[])
|
||||||
ethernet.setIfaceConfig("eth0", {
|
ethernet.setIfaceConfig("eth0", {
|
||||||
mode: 0,
|
mode: 0,
|
||||||
@ -149,12 +149,12 @@ struct Index {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async aboutToAppear() {
|
async aboutToAppear() {
|
||||||
const fileUtil = new FileUtils(this.context)
|
this.fileUtil = new FileUtils(this.context)
|
||||||
const data = await fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt');
|
const data = await this.fileUtil.readFile(GlobalConfig.comoonfileWriteAddress + '/config/ipConfig.txt');
|
||||||
if (data === '' || data === undefined) {
|
if (data === '' || data === undefined) {
|
||||||
} else {
|
} else {
|
||||||
// TODO
|
const result: EnvironmentConfigurationType = JSON.parse(data)
|
||||||
const result: ESObject = JSON.parse(data)
|
AppStorage.setOrCreate<EnvironmentConfigurationType>("EnvironmentConfiguration", result)
|
||||||
this.inputTextList1[9] = result.udplocalIp
|
this.inputTextList1[9] = result.udplocalIp
|
||||||
this.inputTextList1[10] = result.udplocalIpPort
|
this.inputTextList1[10] = result.udplocalIpPort
|
||||||
this.inputTextList1[7] = result.udpOppositeIp
|
this.inputTextList1[7] = result.udpOppositeIp
|
||||||
|
|||||||
@ -625,7 +625,7 @@ struct Index {
|
|||||||
this.oldParam = JSON.parse(JSON.stringify(this.param))
|
this.oldParam = JSON.parse(JSON.stringify(this.param))
|
||||||
this.videoArr = JSON.parse(JSON.stringify(this.videoArr))
|
this.videoArr = JSON.parse(JSON.stringify(this.videoArr))
|
||||||
const folderPath = await this.fileUtil.initFolder(`/config`);
|
const folderPath = await this.fileUtil.initFolder(`/config`);
|
||||||
this.fileUtil.addFile(`${folderPath}/config3.txt`, JSON.stringify(this.param), 'overWrite')
|
this.fileUtil.addFile(`${folderPath}/config3.txt`, JSON.stringify(this.param))
|
||||||
this.showFlag = false
|
this.showFlag = false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user