基于HarmonyOS 5.0开发的WiFi连接调试工具,通过标准WiFi AT指令控制WiFi模块,实现网络连接、数据通信和设备管理功能。支持ESP8266/ESP32等常见WiFi模块,适用于物联网设备调试和网络通信测试。
1. 核心功能
-
AT指令控制:支持发送标准WiFi AT指令
-
WiFi网络管理:扫描、连接、断开WiFi网络
-
TCP通信:建立TCP连接,发送接收数据
-
状态监控:实时显示WiFi连接状态、信号强度、IP地址
-
响应记录:完整记录AT指令发送和响应
2. 支持的AT指令
-
基础指令:AT、AT+RST、AT+GMR等
-
WiFi模式:STA模式、AP模式、混合模式设置
-
网络连接:扫描AP、连接WiFi、断开连接、查看连接状态
-
TCP/IP功能:单连接/多连接模式、建立TCP连接、发送数据、透传模式
-
AP配置:设置AP参数、查看连接设备
3. 界面设计
-
三选项卡布局(指令控制、网络管理、TCP通信)
-
实时状态显示栏
-
响应数据颜色编码区分
-
网络列表可视化展示
-
统计信息卡片展示
4. 模拟特性
-
模拟WiFi网络扫描和连接过程
-
模拟信号强度变化
-
模拟TCP数据通信
-
模拟AT指令响应生成
-
5.适用场景
-
ESP8266/ESP32开发调试
-
物联网设备WiFi配置
-
网络通信测试
-
远程设备监控
-
智能家居设备配置
完整代码
// WiFiATController.ets
import { wifi } from '@kit.ConnectivityKit';
import { common } from '@kit.ArkTS';
// WiFi连接状态枚举
enum WiFiState {
DISCONNECTED = 'disconnected',
SCANNING = 'scanning',
CONNECTING = 'connecting',
CONNECTED = 'connected',
ERROR = 'error'
}
// WiFi网络信息
interface WiFiNetwork {
ssid: string;
bssid: string;
securityType: number;
signalLevel: number;
frequency: number;
timestamp: number;
}
// AT指令响应
interface ATResponse {
timestamp: number;
command: string;
response: string;
status: 'success' | 'error' | 'timeout';
}
@Entry
@Component
struct WiFiATController {
// WiFi状态
@State wifiState: WiFiState = WiFiState.DISCONNECTED;
@State currentSSID: string = '';
@State ipAddress: string = '';
@State macAddress: string = '';
@State signalStrength: number = 0;
// AT指令相关
@State currentCommand: string = '';
@State commandHistory: string[] = [];
@State atResponses: ATResponse[] = [];
// 网络列表
@State wifiNetworks: WiFiNetwork[] = [];
@State selectedNetworkIndex: number = -1;
// 连接参数
@State ssid: string = 'MyWiFi';
@State password: string = 'password123';
@State serverIP: string = '192.168.1.100';
@State serverPort: number = 8080;
@State connectionMode: 'STA' | 'AP' = 'STA';
// TCP/UDP连接
@State tcpConnected: boolean = false;
@State connectionId: number = 0;
@State receivedData: string = '';
// UI状态
@State currentView: string = 'control';
@State showPassword: boolean = false;
@State showServerConfig: boolean = false;
@State autoReconnect: boolean = true;
// 统计信息
@State stats = {
totalCommands: 0,
bytesSent: 0,
bytesReceived: 0,
connectionDuration: 0,
lastConnectedTime: 0
};
// WiFi常用AT指令
private wifiCommands = [
// 基础指令
{ name: 'AT测试', cmd: 'AT', desc: '测试模块响应' },
{ name: '重启模块', cmd: 'AT+RST', desc: '重启WiFi模块' },
{ name: '查看版本', cmd: 'AT+GMR', desc: '查看固件版本' },
// WiFi模式设置
{ name: '设置STA模式', cmd: 'AT+CWMODE=1', desc: '设置为Station模式' },
{ name: '设置AP模式', cmd: 'AT+CWMODE=2', desc: '设置为Access Point模式' },
{ name: '设置混合模式', cmd: 'AT+CWMODE=3', desc: '设置为Station+AP模式' },
// 网络连接
{ name: '扫描网络', cmd: 'AT+CWLAP', desc: '扫描可用WiFi网络' },
{ name: '连接AP', cmd: `AT+CWJAP="${this.ssid}","${this.password}"`, desc: '连接到指定WiFi' },
{ name: '断开连接', cmd: 'AT+CWQAP', desc: '断开WiFi连接' },
{ name: '查看连接', cmd: 'AT+CWJAP?', desc: '查看当前连接状态' },
// TCP/IP功能
{ name: '设置单连接', cmd: 'AT+CIPMUX=0', desc: '设置为单连接模式' },
{ name: '设置多连接', cmd: 'AT+CIPMUX=1', desc: '设置为多连接模式' },
{ name: '建立TCP连接', cmd: `AT+CIPSTART="TCP","${this.serverIP}",${this.serverPort}`, desc: '建立TCP连接' },
{ name: '关闭连接', cmd: 'AT+CIPCLOSE', desc: '关闭TCP连接' },
{ name: '发送数据', cmd: 'AT+CIPSEND=10', desc: '发送指定长度数据' },
{ name: '启用透传', cmd: 'AT+CIPMODE=1', desc: '启用透明传输模式' },
// AP模式设置
{ name: '设置AP参数', cmd: 'AT+CWSAP="ESP8266","password",1,3', desc: '配置AP参数' },
{ name: '查看连接设备', cmd: 'AT+CWLIF', desc: '查看连接到AP的设备' },
// 其他功能
{ name: '查看IP地址', cmd: 'AT+CIFSR', desc: '查看IP地址' },
{ name: '设置串口波特率', cmd: 'AT+CIOBAUD=115200', desc: '设置串口波特率' },
{ name: '深度睡眠', cmd: 'AT+GSLP=3600000', desc: '进入深度睡眠模式' }
];
aboutToAppear() {
// 初始化模拟数据
this.initializeMockNetworks();
// 获取设备信息
this.getDeviceInfo();
// 启动状态更新
this.startStatusMonitor();
}
// 初始化模拟网络列表
initializeMockNetworks() {
const networks: WiFiNetwork[] = [
{ ssid: 'HomeWiFi_5G', bssid: '00:11:22:33:44:55', securityType: 3, signalLevel: 90, frequency: 5745, timestamp: Date.now() },
{ ssid: 'Office_NET', bssid: 'AA:BB:CC:DD:EE:FF', securityType: 2, signalLevel: 75, frequency: 2412, timestamp: Date.now() },
{ ssid: 'Guest_WiFi', bssid: '11:22:33:44:55:66', securityType: 1, signalLevel: 60, frequency: 2437, timestamp: Date.now() },
{ ssid: 'TP-Link_1234', bssid: '22:33:44:55:66:77', securityType: 3, signalLevel: 45, frequency: 2462, timestamp: Date.now() },
{ ssid: 'Huawei_AP', bssid: '33:44:55:66:77:88', securityType: 2, signalLevel: 30, frequency: 2484, timestamp: Date.now() }
];
this.wifiNetworks = networks;
}
// 获取设备信息
getDeviceInfo() {
// 模拟获取设备信息
this.macAddress = 'AA:BB:CC:DD:EE:FF';
this.ipAddress = '192.168.1.' + Math.floor(Math.random() * 100 + 100);
}
// 启动状态监控
startStatusMonitor() {
setInterval(() => {
this.updateWiFiStatus();
this.updateStatistics();
}, 3000);
}
// 更新WiFi状态
updateWiFiStatus() {
// 模拟状态变化
if (this.wifiState === WiFiState.CONNECTED) {
this.signalStrength = Math.floor(Math.random() * 30) + 70;
} else if (this.wifiState === WiFiState.SCANNING) {
this.wifiState = Math.random() > 0.3 ? WiFiState.CONNECTING : WiFiState.DISCONNECTED;
}
// 更新连接时长
if (this.wifiState === WiFiState.CONNECTED && this.stats.lastConnectedTime > 0) {
this.stats.connectionDuration = Math.floor((Date.now() - this.stats.lastConnectedTime) / 1000);
}
}
// 更新统计数据
updateStatistics() {
// 模拟数据增长
if (this.tcpConnected) {
this.stats.bytesReceived += Math.floor(Math.random() * 100);
this.stats.bytesSent += Math.floor(Math.random() * 50);
}
}
// 扫描WiFi网络
scanNetworks() {
this.wifiState = WiFiState.SCANNING;
this.addResponse('AT+CWLAP', '扫描WiFi网络中...', 'success');
// 模拟扫描过程
setTimeout(() => {
this.wifiState = WiFiState.DISCONNECTED;
this.addResponse('AT+CWLAP', this.formatScanResults(), 'success');
}, 2000);
}
// 格式化扫描结果
formatScanResults(): string {
let result = '+CWLAP:(3,"HomeWiFi_5G",-45,"00:11:22:33:44:55",1,5745)\n';
result += '+CWLAP:(2,"Office_NET",-55,"AA:BB:CC:DD:EE:FF",1,2412)\n';
result += '+CWLAP:(1,"Guest_WiFi",-65,"11:22:33:44:55:66",1,2437)\n';
result += 'OK';
return result;
}
// 连接WiFi网络
connectToWiFi() {
if (!this.ssid.trim()) {
this.showToast('请输入SSID');
return;
}
this.wifiState = WiFiState.CONNECTING;
this.addResponse(`AT+CWJAP="${this.ssid}","${this.password}"`, '连接中...', 'success');
// 模拟连接过程
setTimeout(() => {
if (Math.random() > 0.1) { // 90%成功率
this.wifiState = WiFiState.CONNECTED;
this.currentSSID = this.ssid;
this.signalStrength = 85;
this.stats.lastConnectedTime = Date.now();
this.addResponse(`AT+CWJAP="${this.ssid}","${this.password}"`, 'WIFI CONNECTED\nWIFI GOT IP\nOK', 'success');
// 获取IP地址
setTimeout(() => {
this.getIPAddress();
}, 500);
} else {
this.wifiState = WiFiState.ERROR;
this.addResponse(`AT+CWJAP="${this.ssid}","${this.password}"`, 'ERROR\nFAIL', 'error');
}
}, 3000);
}
// 断开WiFi连接
disconnectWiFi() {
this.wifiState = WiFiState.DISCONNECTED;
this.currentSSID = '';
this.ipAddress = '';
this.tcpConnected = false;
this.addResponse('AT+CWQAP', 'OK', 'success');
}
// 获取IP地址
getIPAddress() {
this.addResponse('AT+CIFSR', '查询IP地址...', 'success');
setTimeout(() => {
const response = `+CIFSR:STAIP,"${this.ipAddress}"\n+CIFSR:STAMAC,"${this.macAddress}"\nOK`;
this.addResponse('AT+CIFSR', response, 'success');
}, 500);
}
// 建立TCP连接
establishTCPConnection() {
if (!this.serverIP.trim() || !this.serverPort) {
this.showToast('请配置服务器地址和端口');
return;
}
this.addResponse(`AT+CIPSTART="TCP","${this.serverIP}",${this.serverPort}`, '连接中...', 'success');
setTimeout(() => {
if (Math.random() > 0.15) { // 85%成功率
this.tcpConnected = true;
this.connectionId = 0;
this.addResponse(`AT+CIPSTART="TCP","${this.serverIP}",${this.serverPort}`, 'CONNECT\nOK', 'success');
} else {
this.addResponse(`AT+CIPSTART="TCP","${this.serverIP}",${this.serverPort}`, 'ERROR\nCLOSED', 'error');
}
}, 2000);
}
// 关闭TCP连接
closeTCPConnection() {
this.tcpConnected = false;
this.addResponse('AT+CIPCLOSE', '0,CLOSED\nOK', 'success');
}
// 发送数据
sendData() {
if (!this.tcpConnected) {
this.showToast('请先建立TCP连接');
return;
}
const testData = 'Hello,WiFi! ' + Date.now();
const length = testData.length;
this.addResponse(`AT+CIPSEND=${length}`, '>', 'success');
setTimeout(() => {
// 发送数据
this.addResponse(testData, 'SEND OK', 'success');
this.stats.bytesSent += length;
// 模拟接收响应
setTimeout(() => {
const response = `+IPD,${length}:${testData}`;
this.receivedData = response;
this.stats.bytesReceived += length;
this.addResponse('', response, 'success');
}, 500);
}, 1000);
}
// 发送AT指令
sendATCommand() {
const cmd = this.currentCommand.trim();
if (!cmd) {
this.showToast('请输入AT指令');
return;
}
// 保存到历史记录
this.commandHistory.unshift(cmd);
if (this.commandHistory.length > 20) {
this.commandHistory.pop();
}
// 发送指令
this.addResponse(cmd, '处理中...', 'success');
this.stats.totalCommands++;
// 模拟响应
setTimeout(() => {
this.simulateATResponse(cmd);
}, 500 + Math.random() * 1000);
this.currentCommand = '';
}
// 模拟AT响应
simulateATResponse(command: string) {
let response = '';
let status: 'success' | 'error' | 'timeout' = 'success';
if (command === 'AT') {
response = 'OK';
} else if (command === 'AT+RST') {
response = 'OK';
setTimeout(() => {
this.wifiState = WiFiState.DISCONNECTED;
this.tcpConnected = false;
}, 1000);
} else if (command === 'AT+GMR') {
response = 'AT version:1.7.0.0\nSDK version:3.0.0\ncompile time:Jan 10 2023\nOK';
} else if (command.startsWith('AT+CWMODE=')) {
const mode = command.charAt(10);
response = 'OK';
this.connectionMode = mode === '2' ? 'AP' : 'STA';
} else if (command === 'AT+CWLAP') {
response = this.formatScanResults();
} else if (command.startsWith('AT+CWJAP')) {
response = 'WIFI CONNECTED\nWIFI GOT IP\nOK';
this.wifiState = WiFiState.CONNECTED;
} else if (command === 'AT+CWQAP') {
response = 'OK';
this.wifiState = WiFiState.DISCONNECTED;
} else if (command === 'AT+CWJAP?') {
if (this.wifiState === WiFiState.CONNECTED) {
response = `+CWJAP:"${this.currentSSID}","${this.macAddress}",1,${this.signalStrength},0,0\nOK`;
} else {
response = 'No AP\nOK';
}
} else if (command.startsWith('AT+CIPSTART')) {
response = 'CONNECT\nOK';
this.tcpConnected = true;
} else if (command === 'AT+CIPCLOSE') {
response = '0,CLOSED\nOK';
this.tcpConnected = false;
} else if (command.startsWith('AT+CIPSEND=')) {
response = '>\nSEND OK';
} else if (command === 'AT+CIFSR') {
response = `+CIFSR:STAIP,"${this.ipAddress}"\n+CIFSR:STAMAC,"${this.macAddress}"\nOK`;
} else {
// 默认响应
response = Math.random() > 0.2 ? 'OK' : 'ERROR';
status = response === 'OK' ? 'success' : 'error';
}
// 更新响应
const lastIndex = this.atResponses.length - 1;
if (lastIndex >= 0) {
this.atResponses[lastIndex] = {
...this.atResponses[lastIndex],
response: response,
status: status
};
}
}
// 添加响应记录
addResponse(command: string, response: string, status: 'success' | 'error' | 'timeout') {
this.atResponses.unshift({
timestamp: Date.now(),
command: command,
response: response,
status: status
});
if (this.atResponses.length > 50) {
this.atResponses.pop();
}
}
// 清空响应记录
clearResponses() {
this.atResponses = [];
}
// 选择网络
selectNetwork(index: number) {
this.selectedNetworkIndex = index;
const network = this.wifiNetworks[index];
if (network) {
this.ssid = network.ssid;
}
}
// 获取WiFi状态颜色
getWiFiColor(): string {
switch (this.wifiState) {
case WiFiState.CONNECTED: return '#4CAF50';
case WiFiState.CONNECTING: return '#FFC107';
case WiFiState.SCANNING: return '#2196F3';
case WiFiState.ERROR: return '#F44336';
default: return '#757575';
}
}
// 获取WiFi状态文本
getWiFiText(): string {
switch (this.wifiState) {
case WiFiState.CONNECTED: return '已连接';
case WiFiState.CONNECTING: return '连接中';
case WiFiState.SCANNING: return '扫描中';
case WiFiState.ERROR: return '连接错误';
default: return '未连接';
}
}
// 获取信号强度图标
getSignalIcon(level: number): string {
if (level >= 80) return '📶';
if (level >= 60) return '📶';
if (level >= 40) return '📶';
if (level >= 20) return '📶';
return '📶';
}
// 获取安全类型文本
getSecurityText(type: number): string {
switch (type) {
case 1: return 'WEP';
case 2: return 'WPA-PSK';
case 3: return 'WPA2-PSK';
case 4: return 'WPA/WPA2';
default: return '开放';
}
}
// 显示提示
showToast(message: string) {
console.log('Toast:', message);
}
build() {
Column({ space: 0 }) {
// 顶部状态栏
Row({ space: 12 }) {
// WiFi状态
Row({ space: 8 }) {
Circle({ width: 12, height: 12 })
.fill(this.getWiFiColor())
Column({ space: 2 }) {
Text(this.getWiFiText())
.fontSize(14)
.fontColor(this.getWiFiColor())
if (this.wifiState === WiFiState.CONNECTED) {
Text(this.currentSSID)
.fontSize(10)
.fontColor('#666666')
}
}
}
.layoutWeight(1)
// 连接信息
if (this.wifiState === WiFiState.CONNECTED) {
Row({ space: 12 }) {
Column({ space: 2 }) {
Text(this.ipAddress)
.fontSize(12)
.fontColor('#2196F3')
Text('IP地址')
.fontSize(10)
.fontColor('#666666')
}
Column({ space: 2 }) {
Text(this.signalStrength + '%')
.fontSize(12)
.fontColor('#FF9800')
Text('信号强度')
.fontSize(10)
.fontColor('#666666')
}
if (this.tcpConnected) {
Badge({
count: 'TCP已连接',
position: BadgePosition.Right,
color: '#4CAF50'
})
}
}
}
}
.width('100%')
.padding(16)
.backgroundColor('#FFFFFF')
.border({ bottom: { width: 1, color: '#E0E0E0' } })
// 选项卡
Row({ space: 0 }) {
Button('指令控制')
.fontSize(14)
.fontColor(this.currentView === 'control' ? '#2196F3' : '#666666')
.backgroundColor(this.currentView === 'control' ? '#E3F2FD' : 'transparent')
.layoutWeight(1)
.height(48)
.borderRadius(0)
.onClick(() => { this.currentView = 'control'; })
Button('网络管理')
.fontSize(14)
.fontColor(this.currentView === 'network' ? '#2196F3' : '#666666')
.backgroundColor(this.currentView === 'network' ? '#E3F2FD' : 'transparent')
.layoutWeight(1)
.height(48)
.borderRadius(0)
.onClick(() => { this.currentView = 'network'; })
Button('TCP通信')
.fontSize(14)
.fontColor(this.currentView === 'tcp' ? '#2196F3' : '#666666')
.backgroundColor(this.currentView === 'tcp' ? '#E3F2FD' : 'transparent')
.layoutWeight(1)
.height(48)
.borderRadius(0)
.onClick(() => { this.currentView = 'tcp'; })
}
.width('100%')
.border({ bottom: { width: 1, color: '#E0E0E0' } })
// 内容区域
Scroll() {
Column({ space: 16 }) {
// 指令控制视图
if (this.currentView === 'control') {
// AT指令输入
Column({ space: 8 }) {
Row({ space: 8 }) {
Text('📟')
.fontSize(20)
Text('AT指令控制台')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
}
Row({ space: 8 }) {
TextInput({ text: this.currentCommand })
.layoutWeight(1)
.fontSize(14)
.backgroundColor('#F5F5F5')
.onChange((value: string) => {
this.currentCommand = value;
})
Button('发送')
.fontSize(14)
.fontColor('#FFFFFF')
.backgroundColor('#2196F3')
.padding({ left: 16, right: 16 })
.height(40)
.borderRadius(20)
.onClick(() => {
this.sendATCommand();
})
}
// 常用指令快捷按钮
Scroll(.horizontal) {
Row({ space: 8 }) {
ForEach(this.wifiCommands.slice(0, 10), (cmd: any) => {
Button(cmd.name)
.fontSize(12)
.fontColor('#2196F3')
.backgroundColor('#E3F2FD')
.padding({ left: 12, right: 12, top: 6, bottom: 6 })
.borderRadius(16)
.onClick(() => {
this.currentCommand = cmd.cmd;
})
})
}
.padding({ top: 8, bottom: 8 })
}
.scrollable(ScrollDirection.Horizontal)
}
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(12)
.margin({ top: 12, left: 16, right: 16 })
// 响应记录
Column({ space: 8 }) {
Row({ space: 8 }) {
Text('📥')
.fontSize(20)
Text('响应记录')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Text(`(${this.atResponses.length})`)
.fontSize(12)
.fontColor('#666666')
Row({ space: 8 })
.layoutWeight(1)
Button('清空')
.fontSize(12)
.fontColor('#F44336')
.backgroundColor(Color.Transparent)
.onClick(() => {
this.clearResponses();
})
}
// 响应列表
Column({ space: 4 }) {
ForEach(this.atResponses.slice(0, 10), (response: ATResponse, index: number) => {
this.buildResponseItem(response, index);
})
}
.height(300)
.border({ width: 1, color: '#E0E0E0' })
.borderRadius(8)
.padding(8)
}
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(12)
.margin({ left: 16, right: 16 })
}
// 网络管理视图
if (this.currentView === 'network') {
Column({ space: 16 }) {
// WiFi连接设置
Column({ space: 12 }) {
Row({ space: 8 }) {
Text('📡')
.fontSize(20)
Text('WiFi连接')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
}
Column({ space: 8 }) {
Text('WiFi名称 (SSID)')
.fontSize(14)
.fontColor('#666666')
TextInput({ text: this.ssid })
.width('100%')
.fontSize(14)
.backgroundColor('#F5F5F5')
.onChange((value: string) => {
this.ssid = value;
})
}
Column({ space: 8 }) {
Row({ space: 8 }) {
Text('WiFi密码')
.fontSize(14)
.fontColor('#666666')
.layoutWeight(1)
Button(this.showPassword ? '隐藏' : '显示')
.fontSize(12)
.fontColor('#2196F3')
.backgroundColor(Color.Transparent)
.onClick(() => {
this.showPassword = !this.showPassword;
})
}
TextInput({ text: this.password })
.width('100%')
.fontSize(14)
.backgroundColor('#F5F5F5')
.type(this.showPassword ? InputType.Normal : InputType.Password)
.onChange((value: string) => {
this.password = value;
})
}
Row({ space: 12 }) {
Button('扫描网络')
.fontSize(14)
.fontColor('#2196F3')
.backgroundColor('#E3F2FD')
.layoutWeight(1)
.height(48)
.borderRadius(24)
.onClick(() => {
this.scanNetworks();
})
if (this.wifiState === WiFiState.CONNECTED) {
Button('断开连接')
.fontSize(14)
.fontColor('#F44336')
.backgroundColor('#FFEBEE')
.layoutWeight(1)
.height(48)
.borderRadius(24)
.onClick(() => {
this.disconnectWiFi();
})
} else {
Button('连接WiFi')
.fontSize(14)
.fontColor('#FFFFFF')
.backgroundColor('#4CAF50')
.layoutWeight(1)
.height(48)
.borderRadius(24)
.onClick(() => {
this.connectToWiFi();
})
}
}
}
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(12)
// 可用网络列表
Column({ space: 8 }) {
Row({ space: 8 }) {
Text('📶')
.fontSize(20)
Text('可用网络')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Text(`(${this.wifiNetworks.length})`)
.fontSize(12)
.fontColor('#666666')
}
Column({ space: 8 }) {
ForEach(this.wifiNetworks, (network: WiFiNetwork, index: number) => {
this.buildNetworkItem(network, index);
})
}
}
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(12)
}
.padding(16)
}
// TCP通信视图
if (this.currentView === 'tcp') {
Column({ space: 16 }) {
// 服务器设置
Column({ space: 12 }) {
Row({ space: 8 }) {
Text('🌐')
.fontSize(20)
Text('服务器设置')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
}
Row({ space: 12 }) {
Column({ space: 8 }) {
Text('服务器IP')
.fontSize(14)
.fontColor('#666666')
TextInput({ text: this.serverIP })
.width('100%')
.fontSize(14)
.backgroundColor('#F5F5F5')
.onChange((value: string) => {
this.serverIP = value;
})
}
Column({ space: 8 }) {
Text('端口')
.fontSize(14)
.fontColor('#666666')
TextInput({ text: this.serverPort.toString() })
.width(100)
.fontSize(14)
.backgroundColor('#F5F5F5')
.onChange((value: string) => {
this.serverPort = parseInt(value) || 8080;
})
}
}
Row({ space: 12 }) {
if (this.tcpConnected) {
Button('断开TCP')
.fontSize(14)
.fontColor('#F44336')
.backgroundColor('#FFEBEE')
.layoutWeight(1)
.height(48)
.borderRadius(24)
.onClick(() => {
this.closeTCPConnection();
})
} else {
Button('连接TCP')
.fontSize(14)
.fontColor('#FFFFFF')
.backgroundColor('#2196F3')
.layoutWeight(1)
.height(48)
.borderRadius(24)
.onClick(() => {
this.establishTCPConnection();
})
.enabled(this.wifiState === WiFiState.CONNECTED)
}
Button('发送测试数据')
.fontSize(14)
.fontColor('#FFFFFF')
.backgroundColor('#4CAF50')
.layoutWeight(1)
.height(48)
.borderRadius(24)
.onClick(() => {
this.sendData();
})
.enabled(this.tcpConnected)
}
}
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(12)
// 数据通信
Column({ space: 8 }) {
Row({ space: 8 }) {
Text('📨')
.fontSize(20)
Text('数据通信')
.fontSize(16)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
}
Column({ space: 8 }) {
Text('接收到的数据')
.fontSize(14)
.fontColor('#666666')
Text(this.receivedData || '暂无数据')
.fontSize(12)
.fontColor('#333333')
.width('100%')
.padding(12)
.backgroundColor('#F5F5F5')
.borderRadius(8)
.height(100)
}
// 统计信息
Grid() {
GridItem() {
this.buildStatCard('发送字节', this.stats.bytesSent.toString(), '#2196F3');
}
GridItem() {
this.buildStatCard('接收字节', this.stats.bytesReceived.toString(), '#4CAF50');
}
GridItem() {
this.buildStatCard('指令数', this.stats.totalCommands.toString(), '#FF9800');
}
GridItem() {
this.buildStatCard('连接时长', this.stats.connectionDuration + '秒', '#9C27B0');
}
}
.columnsTemplate('1fr 1fr')
.rowsTemplate('1fr 1fr')
.columnsGap(12)
.rowsGap(12)
}
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(12)
}
.padding(16)
}
}
}
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.Auto)
.margin({ bottom: 60 })
}
.width('100%')
.height('100%')
.backgroundColor('#F5F5F5')
}
// 构建响应项
@Builder
buildResponseItem(response: ATResponse, index: number) {
Column({ space: 4 }) {
Row({ space: 8 }) {
Text(new Date(response.timestamp).toLocaleTimeString())
.fontSize(10)
.fontColor('#999999')
Circle({ width: 6, height: 6 })
.fill(response.status === 'success' ? '#4CAF50' :
response.status === 'error' ? '#F44336' : '#FF9800')
}
Text('> ' + response.command)
.fontSize(12)
.fontColor('#2196F3')
.fontFamily('monospace')
if (response.response) {
Text(response.response.split('\n').map(line => '< ' + line).join('\n'))
.fontSize(12)
.fontColor('#4CAF50')
.fontFamily('monospace')
.margin({ top: 4 })
}
}
.width('100%')
.padding(8)
.backgroundColor(index % 2 === 0 ? '#F9F9F9' : '#FFFFFF')
.borderRadius(4)
}
// 构建网络项
@Builder
buildNetworkItem(network: WiFiNetwork, index: number) {
Row({ space: 12 }) {
Column({ space: 4 }) {
Text(this.getSignalIcon(network.signalLevel))
.fontSize(16)
Text(network.signalLevel + '%')
.fontSize(10)
.fontColor('#666666')
}
Column({ space: 4 }) {
Row({ space: 8 }) {
Text(network.ssid)
.fontSize(14)
.fontWeight(FontWeight.Medium)
.fontColor('#333333')
Badge({
count: this.getSecurityText(network.securityType),
position: BadgePosition.Right,
color: '#2196F3',
style: { fontSize: 10 }
})
}
Text(network.bssid)
.fontSize(11)
.fontColor('#666666')
}
.layoutWeight(1)
if (this.selectedNetworkIndex === index) {
Icon({ src: $r('app.media.ic_check'), size: { width: 20, height: 20 } })
.fill('#4CAF50')
}
}
.width('100%')
.padding(12)
.backgroundColor(this.selectedNetworkIndex === index ? '#E8F5E9' : '#F5F5F5')
.borderRadius(8)
.onClick(() => {
this.selectNetwork(index);
})
}
// 构建统计卡片
@Builder
buildStatCard(title: string, value: string, color: string) {
Column({ space: 6 }) {
Text(value)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.fontColor(color)
Text(title)
.fontSize(10)
.fontColor('#666666')
}
.width('100%')
.padding(12)
.backgroundColor('#FFFFFF')
.borderRadius(8)
.border({ width: 1, color: '#E0E0E0' })
}
}
想入门鸿蒙开发又怕花冤枉钱?别错过!现在能免费系统学 -- 从 ArkTS 面向对象核心的类和对象、继承多态,到吃透鸿蒙开发关键技能,还能冲刺鸿蒙基础 +高级开发者证书,更惊喜的是考证成功还送好礼!快加入我的鸿蒙班,一起从入门到精通,班级链接:点击https://developer.huawei.com/consumer/cn/training/classDetail/b7365031334e4353a9a0fd6785bb0791?type=1?ha_source=hmosclass\&ha_sourceId=89000248免费进入