这是一个完整的HarmonyOS 5.0物联网控制器应用,具有以下特点:

1. 核心功能

  • 多协议支持:TCP、UDP、MQTT、HTTP协议切换

  • 设备管理:添加、删除、连接、断开物联网设备

  • 批量操作:支持设备批量控制

  • 数据透传:文本/十六进制格式双向数据传输

  • 实时监控:设备状态、网络状态实时显示

  • 自动重连:支持设备自动重连机制

2. HarmonyOS 5.0特性

  • 使用ArkTS声明式UI

  • 网络连接状态监听

  • Socket通信基础框架

  • 响应式数据绑定

  • 现代化的组件设计

3. 界面设计

  • 三选项卡布局(设备管理、数据透传、监控中心)

  • 实时状态指示器

  • 卡片式设备列表

  • 数据收发分离界面

  • 暗色/亮色主题适配

4. 通信机制

  • 模拟设备心跳检测

  • 自动设备状态更新

  • 数据格式转换

  • 错误处理和重连逻辑

// 4GTransparentController.ets
import { socket, netConnection, notification } from '@kit.ArkNetworkKit';
import { network } from '@kit.NetworkKit';
import { deviceInfo } from '@kit.DeviceInfoKit';

// 设备数据结构
interface IoTDevice {
  id: string;
  name: string;
  ipAddress: string;
  port: number;
  protocol: string;
  status: 'online' | 'offline' | 'connecting';
  lastData: string;
  lastUpdate: number;
  isSelected: boolean;
}

// 通信协议类型
enum ProtocolType {
  TCP = 'TCP',
  UDP = 'UDP',
  MQTT = 'MQTT',
  HTTP = 'HTTP'
}

// 网络状态
enum NetworkState {
  DISCONNECTED = 'disconnected',
  CONNECTING = 'connecting',
  CONNECTED = 'connected',
  ERROR = 'error'
}

@Entry
@Component
struct FourGTransparentController {
  // 设备管理
  @State devices: IoTDevice[] = [];
  @State selectedDevices: string[] = [];
  
  // 网络连接状态
  @State networkState: NetworkState = NetworkState.DISCONNECTED;
  @State connectionType: string = '4G';
  @State signalStrength: number = 4;
  
  // 数据传输
  @State sendData: string = '';
  @State receivedData: string[] = [];
  @State dataFormat: 'hex' | 'text' = 'text';
  @State currentProtocol: ProtocolType = ProtocolType.TCP;
  
  // 通信参数
  @State serverAddress: string = '192.168.1.100';
  @State serverPort: number = 8080;
  @State autoReconnect: boolean = true;
  
  // UI状态
  @State currentView: string = 'dashboard';
  @State showAddDevice: boolean = false;
  @State showSettings: boolean = false;
  @State newDevice: IoTDevice = {
    id: '',
    name: '',
    ipAddress: '',
    port: 0,
    protocol: 'TCP',
    status: 'offline',
    lastData: '',
    lastUpdate: 0,
    isSelected: false
  };
  
  // 统计信息
  @State stats = {
    totalDevices: 0,
    onlineDevices: 0,
    totalDataSent: 0,
    totalDataReceived: 0,
    connectionTime: 0
  };
  
  // Socket相关
  private tcpSocket: socket.TCPSocket = null;
  private udpSocket: socket.UDPSocket = null;
  private connectionTimer: number = 0;
  private lastHeartbeat: number = 0;
  
  aboutToAppear() {
    // 初始化示例设备
    this.initializeSampleDevices();
    
    // 检查网络状态
    this.checkNetworkStatus();
    
    // 开始心跳检测
    this.startHeartbeat();
  }
  
  aboutToDisappear() {
    // 清理资源
    this.disconnectAll();
    clearInterval(this.connectionTimer);
  }
  
  // 初始化示例设备
  initializeSampleDevices() {
    const sampleDevices: IoTDevice[] = [
      {
        id: 'dev001',
        name: '温室传感器',
        ipAddress: '192.168.1.101',
        port: 502,
        protocol: 'TCP',
        status: 'online',
        lastData: '温度:24.5°C 湿度:65%',
        lastUpdate: Date.now(),
        isSelected: false
      },
      {
        id: 'dev002',
        name: '水泵控制器',
        ipAddress: '192.168.1.102',
        port: 503,
        protocol: 'UDP',
        status: 'online',
        lastData: '状态:运行中 流量:5.2L/s',
        lastUpdate: Date.now() - 30000,
        isSelected: false
      },
      {
        id: 'dev003',
        name: '照明系统',
        ipAddress: '192.168.1.103',
        port: 1883,
        protocol: 'MQTT',
        status: 'offline',
        lastData: '亮度:75% 功率:120W',
        lastUpdate: Date.now() - 60000,
        isSelected: false
      },
      {
        id: 'dev004',
        name: '气象站',
        ipAddress: '192.168.1.104',
        port: 80,
        protocol: 'HTTP',
        status: 'connecting',
        lastData: '风速:3.2m/s 雨量:0mm',
        lastUpdate: Date.now() - 120000,
        isSelected: false
      }
    ];
    
    this.devices = sampleDevices;
    this.updateStats();
  }
  
  // 检查网络状态
  async checkNetworkStatus() {
    try {
      // 获取网络信息
      const netHandle = network.getDefaultNet();
      const linkInfo = await netHandle.getLinkProperties();
      
      this.networkState = NetworkState.CONNECTED;
      this.connectionType = linkInfo.linkAddresses[0]?.type || '4G';
      
      // 模拟信号强度
      this.signalStrength = Math.floor(Math.random() * 5) + 1;
    } catch (error) {
      console.error('检查网络状态失败:', error);
      this.networkState = NetworkState.DISCONNECTED;
    }
  }
  
  // 开始心跳检测
  startHeartbeat() {
    this.connectionTimer = setInterval(() => {
      this.lastHeartbeat = Date.now();
      
      // 更新设备状态
      this.updateDeviceStatus();
      
      // 重新检查网络
      this.checkNetworkStatus();
      
      // 自动重连
      if (this.autoReconnect) {
        this.autoReconnectDevices();
      }
    }, 10000);
  }
  
  // 更新设备状态
  updateDeviceStatus() {
    this.devices = this.devices.map(device => {
      const timeDiff = Date.now() - device.lastUpdate;
      
      // 模拟设备状态变化
      if (timeDiff > 120000 && device.status === 'online') {
        return { ...device, status: 'offline' };
      } else if (timeDiff < 30000 && device.status === 'offline') {
        return { ...device, status: 'online' };
      }
      
      return device;
    });
    
    this.updateStats();
  }
  
  // 自动重连设备
  autoReconnectDevices() {
    const offlineDevices = this.devices.filter(d => d.status === 'offline');
    
    offlineDevices.forEach(device => {
      // 模拟重连
      setTimeout(() => {
        const index = this.devices.findIndex(d => d.id === device.id);
        if (index !== -1 && Math.random() > 0.3) {
          this.devices[index] = {
            ...this.devices[index],
            status: 'online',
            lastUpdate: Date.now()
          };
          this.updateStats();
        }
      }, Math.random() * 3000);
    });
  }
  
  // 更新统计信息
  updateStats() {
    const onlineDevices = this.devices.filter(d => d.status === 'online').length;
    
    this.stats = {
      totalDevices: this.devices.length,
      onlineDevices: onlineDevices,
      totalDataSent: this.stats.totalDataSent,
      totalDataReceived: this.stats.totalDataReceived,
      connectionTime: Math.floor((Date.now() - this.lastHeartbeat) / 1000) + this.stats.connectionTime
    };
  }
  
  // 添加新设备
  addNewDevice() {
    if (!this.newDevice.name.trim() || !this.newDevice.ipAddress.trim()) {
      return;
    }
    
    const newDevice: IoTDevice = {
      ...this.newDevice,
      id: 'dev' + Date.now().toString().slice(-6),
      status: 'offline',
      lastUpdate: Date.now() - 60000
    };
    
    this.devices.push(newDevice);
    this.newDevice = {
      id: '',
      name: '',
      ipAddress: '',
      port: 0,
      protocol: 'TCP',
      status: 'offline',
      lastData: '',
      lastUpdate: 0,
      isSelected: false
    };
    
    this.showAddDevice = false;
    this.updateStats();
  }
  
  // 删除设备
  deleteDevice(deviceId: string) {
    this.devices = this.devices.filter(device => device.id !== deviceId);
    this.updateStats();
  }
  
  // 选择/取消选择设备
  toggleDeviceSelection(deviceId: string) {
    const index = this.devices.findIndex(d => d.id === deviceId);
    if (index !== -1) {
      this.devices[index].isSelected = !this.devices[index].isSelected;
    }
    
    // 更新选择列表
    this.selectedDevices = this.devices
      .filter(d => d.isSelected)
      .map(d => d.id);
  }
  
  // 批量控制设备
  batchControlDevices(action: string) {
    const selected = this.devices.filter(d => d.isSelected);
    
    selected.forEach(device => {
      switch (action) {
        case 'connect':
          this.connectToDevice(device);
          break;
        case 'disconnect':
          this.disconnectDevice(device);
          break;
        case 'restart':
          this.restartDevice(device);
          break;
      }
    });
  }
  
  // 连接到设备
  connectToDevice(device: IoTDevice) {
    const index = this.devices.findIndex(d => d.id === device.id);
    if (index === -1) return;
    
    this.devices[index].status = 'connecting';
    
    // 模拟连接过程
    setTimeout(() => {
      if (Math.random() > 0.2) { // 80%成功率
        this.devices[index] = {
          ...this.devices[index],
          status: 'online',
          lastUpdate: Date.now(),
          lastData: '连接成功'
        };
        this.addReceivedData(`设备 ${device.name} 连接成功`);
      } else {
        this.devices[index].status = 'offline';
        this.addReceivedData(`设备 ${device.name} 连接失败`);
      }
      this.updateStats();
    }, 1000);
  }
  
  // 断开设备连接
  disconnectDevice(device: IoTDevice) {
    const index = this.devices.findIndex(d => d.id === device.id);
    if (index === -1) return;
    
    this.devices[index].status = 'offline';
    this.addReceivedData(`设备 ${device.name} 已断开`);
    this.updateStats();
  }
  
  // 重启设备
  restartDevice(device: IoTDevice) {
    const index = this.devices.findIndex(d => d.id === device.id);
    if (index === -1) return;
    
    this.devices[index].status = 'connecting';
    this.addReceivedData(`设备 ${device.name} 正在重启...`);
    
    setTimeout(() => {
      this.devices[index] = {
        ...this.devices[index],
        status: 'online',
        lastUpdate: Date.now(),
        lastData: '重启完成'
      };
      this.addReceivedData(`设备 ${device.name} 重启完成`);
      this.updateStats();
    }, 2000);
  }
  
  // 断开所有连接
  disconnectAll() {
    this.devices = this.devices.map(device => ({
      ...device,
      status: 'offline',
      isSelected: false
    }));
    
    this.selectedDevices = [];
    this.addReceivedData('所有设备已断开连接');
    this.updateStats();
  }
  
  // 发送数据
  sendDataToDevices() {
    if (!this.sendData.trim()) return;
    
    const selected = this.devices.filter(d => d.isSelected && d.status === 'online');
    
    if (selected.length === 0) {
      this.addReceivedData('错误:请先选择在线的设备');
      return;
    }
    
    // 格式转换
    let dataToSend = this.sendData;
    if (this.dataFormat === 'hex') {
      // 简单的十六进制转换
      dataToSend = this.convertToHex(this.sendData);
    }
    
    selected.forEach(device => {
      this.addReceivedData(`发送到 ${device.name}: ${dataToSend}`);
      
      // 模拟设备响应
      setTimeout(() => {
        const response = `设备 ${device.name} 响应: ${this.generateResponse(dataToSend)}`;
        this.addReceivedData(response);
        
        // 更新设备数据
        const index = this.devices.findIndex(d => d.id === device.id);
        if (index !== -1) {
          this.devices[index].lastData = response;
          this.devices[index].lastUpdate = Date.now();
        }
      }, 500 + Math.random() * 1000);
    });
    
    // 更新统计
    this.stats.totalDataSent += dataToSend.length;
    this.sendData = '';
  }
  
  // 生成响应数据
  generateResponse(input: string): string {
    const responses = [
      `收到数据 ${input.length} 字节`,
      `处理完成`,
      `执行成功`,
      `数据校验通过`,
      `状态已更新`
    ];
    return responses[Math.floor(Math.random() * responses.length)];
  }
  
  // 转换为十六进制
  convertToHex(str: string): string {
    return str.split('')
      .map(c => c.charCodeAt(0).toString(16).padStart(2, '0'))
      .join(' ');
  }
  
  // 添加接收数据
  addReceivedData(data: string) {
    const timestamp = new Date().toLocaleTimeString();
    this.receivedData.unshift(`[${timestamp}] ${data}`);
    
    // 限制历史记录数量
    if (this.receivedData.length > 50) {
      this.receivedData.pop();
    }
    
    this.stats.totalDataReceived += data.length;
  }
  
  // 清空接收数据
  clearReceivedData() {
    this.receivedData = [];
  }
  
  // 获取网络状态颜色
  getNetworkColor(): string {
    switch (this.networkState) {
      case NetworkState.CONNECTED: return '#4CAF50';
      case NetworkState.CONNECTING: return '#FFC107';
      case NetworkState.DISCONNECTED: return '#F44336';
      default: return '#9E9E9E';
    }
  }
  
  // 获取网络状态文本
  getNetworkText(): string {
    switch (this.networkState) {
      case NetworkState.CONNECTED: return '已连接';
      case NetworkState.CONNECTING: return '连接中';
      case NetworkState.DISCONNECTED: return '未连接';
      default: return '未知';
    }
  }
  
  // 获取信号强度图标
  getSignalIcon(): string {
    switch (this.signalStrength) {
      case 5: return '📶';
      case 4: return '📶';
      case 3: return '📶';
      case 2: return '📶';
      case 1: return '📶';
      default: return '📴';
    }
  }
  
  // 获取设备状态颜色
  getDeviceStatusColor(status: string): string {
    switch (status) {
      case 'online': return '#4CAF50';
      case 'connecting': return '#FFC107';
      case 'offline': return '#F44336';
      default: return '#9E9E9E';
    }
  }
  
  build() {
    Column({ space: 0 }) {
      // 顶部状态栏
      Row({ space: 12 }) {
        // 网络状态
        Row({ space: 8 }) {
          Text(this.getSignalIcon())
            .fontSize(20)
          
          Column({ space: 2 }) {
            Text(this.getNetworkText())
              .fontSize(12)
              .fontColor(this.getNetworkColor())
            
            Text(this.connectionType)
              .fontSize(10)
              .fontColor('#666666')
          }
        }
        .layoutWeight(1)
        
        // 统计信息
        Row({ space: 16 }) {
          Column({ space: 2 }) {
            Text(this.stats.onlineDevices.toString())
              .fontSize(16)
              .fontWeight(FontWeight.Bold)
              .fontColor('#2196F3')
            
            Text('在线')
              .fontSize(10)
              .fontColor('#666666')
          }
          
          Column({ space: 2 }) {
            Text(this.stats.totalDevices.toString())
              .fontSize(16)
              .fontWeight(FontWeight.Bold)
              .fontColor('#757575')
            
            Text('设备')
              .fontSize(10)
              .fontColor('#666666')
          }
        }
      }
      .width('100%')
      .padding(16)
      .backgroundColor('#FFFFFF')
      .border({ bottom: { width: 1, color: '#E0E0E0' } })
      
      // 选项卡
      Row({ space: 0 }) {
        Button('设备管理')
          .fontSize(14)
          .fontColor(this.currentView === 'devices' ? '#2196F3' : '#666666')
          .backgroundColor(this.currentView === 'devices' ? '#E3F2FD' : 'transparent')
          .layoutWeight(1)
          .height(48)
          .borderRadius(0)
          .onClick(() => { this.currentView = 'devices'; })
        
        Button('数据透传')
          .fontSize(14)
          .fontColor(this.currentView === 'transmission' ? '#2196F3' : '#666666')
          .backgroundColor(this.currentView === 'transmission' ? '#E3F2FD' : 'transparent')
          .layoutWeight(1)
          .height(48)
          .borderRadius(0)
          .onClick(() => { this.currentView = 'transmission'; })
        
        Button('监控中心')
          .fontSize(14)
          .fontColor(this.currentView === 'monitor' ? '#2196F3' : '#666666')
          .backgroundColor(this.currentView === 'monitor' ? '#E3F2FD' : 'transparent')
          .layoutWeight(1)
          .height(48)
          .borderRadius(0)
          .onClick(() => { this.currentView = 'monitor'; })
      }
      .width('100%')
      .border({ bottom: { width: 1, color: '#E0E0E0' } })
      
      // 内容区域
      Scroll() {
        Column({ space: 16 }) {
          // 设备管理视图
          if (this.currentView === 'devices') {
            // 批量操作栏
            Row({ space: 12 }) {
              Button('全选')
                .fontSize(12)
                .fontColor('#2196F3')
                .backgroundColor('#E3F2FD')
                .padding({ left: 12, right: 12, top: 6, bottom: 6 })
                .borderRadius(16)
                .onClick(() => {
                  this.devices = this.devices.map(d => ({ ...d, isSelected: true }));
                  this.selectedDevices = this.devices.map(d => d.id);
                })
              
              Button('连接选中')
                .fontSize(12)
                .fontColor('#4CAF50')
                .backgroundColor('#E8F5E9')
                .padding({ left: 12, right: 12, top: 6, bottom: 6 })
                .borderRadius(16)
                .onClick(() => {
                  this.batchControlDevices('connect');
                })
              
              Button('断开选中')
                .fontSize(12)
                .fontColor('#F44336')
                .backgroundColor('#FFEBEE')
                .padding({ left: 12, right: 12, top: 6, bottom: 6 })
                .borderRadius(16)
                .onClick(() => {
                  this.batchControlDevices('disconnect');
                })
              
              Button('+添加')
                .fontSize(12)
                .fontColor('#FFFFFF')
                .backgroundColor('#2196F3')
                .padding({ left: 12, right: 12, top: 6, bottom: 6 })
                .borderRadius(16)
                .onClick(() => {
                  this.showAddDevice = true;
                })
            }
            .width('100%')
            .padding(16)
            
            // 设备列表
            Column({ space: 12 }) {
              ForEach(this.devices, (device: IoTDevice) => {
                this.buildDeviceCard(device);
              })
            }
            .width('100%')
            .padding({ left: 16, right: 16 })
          }
          
          // 数据透传视图
          if (this.currentView === 'transmission') {
            Column({ space: 16 }) {
              // 协议设置
              Row({ space: 12 }) {
                Column({ space: 4 }) {
                  Text('通信协议')
                    .fontSize(14)
                    .fontColor('#666666')
                  
                  Row({ space: 8 }) {
                    ForEach(['TCP', 'UDP', 'MQTT', 'HTTP'], (protocol: string) => {
                      Button(protocol)
                        .fontSize(12)
                        .fontColor(this.currentProtocol === protocol ? '#FFFFFF' : '#2196F3')
                        .backgroundColor(this.currentProtocol === protocol ? '#2196F3' : '#E3F2FD')
                        .padding({ left: 12, right: 12, top: 6, bottom: 6 })
                        .borderRadius(16)
                        .onClick(() => {
                          this.currentProtocol = protocol as ProtocolType;
                        })
                    })
                  }
                }
              }
              .width('100%')
              .padding(16)
              .backgroundColor('#FFFFFF')
              .borderRadius(12)
              
              // 数据格式选择
              Row({ space: 16 }) {
                Button('文本模式')
                  .fontSize(14)
                  .fontColor(this.dataFormat === 'text' ? '#FFFFFF' : '#2196F3')
                  .backgroundColor(this.dataFormat === 'text' ? '#2196F3' : '#E3F2FD')
                  .layoutWeight(1)
                  .height(40)
                  .borderRadius(20)
                  .onClick(() => { this.dataFormat = 'text'; })
                
                Button('十六进制')
                  .fontSize(14)
                  .fontColor(this.dataFormat === 'hex' ? '#FFFFFF' : '#2196F3')
                  .backgroundColor(this.dataFormat === 'hex' ? '#2196F3' : '#E3F2FD')
                  .layoutWeight(1)
                  .height(40)
                  .borderRadius(20)
                  .onClick(() => { this.dataFormat = 'hex'; })
              }
              .width('100%')
              .padding({ left: 16, right: 16 })
              
              // 数据发送区域
              Column({ space: 8 }) {
                Text('发送数据')
                  .fontSize(14)
                  .fontColor('#666666')
                  .width('100%')
                
                TextArea({ text: this.sendData })
                  .width('100%')
                  .height(100)
                  .fontSize(14)
                  .backgroundColor('#F5F5F5')
                  .onChange((value: string) => {
                    this.sendData = value;
                  })
                
                Row({ space: 12 }) {
                  Button('发送')
                    .fontSize(16)
                    .fontWeight(FontWeight.Medium)
                    .fontColor('#FFFFFF')
                    .backgroundColor('#2196F3')
                    .layoutWeight(2)
                    .height(48)
                    .borderRadius(24)
                    .onClick(() => {
                      this.sendDataToDevices();
                    })
                  
                  Button('清空')
                    .fontSize(16)
                    .fontWeight(FontWeight.Medium)
                    .fontColor('#666666')
                    .backgroundColor('#F5F5F5')
                    .layoutWeight(1)
                    .height(48)
                    .borderRadius(24)
                    .onClick(() => {
                      this.sendData = '';
                    })
                }
                .width('100%')
              }
              .padding(16)
              .backgroundColor('#FFFFFF')
              .borderRadius(12)
              .margin({ left: 16, right: 16 })
              
              // 接收数据区域
              Column({ space: 8 }) {
                Row({ space: 12 }) {
                  Text('接收数据')
                    .fontSize(14)
                    .fontColor('#666666')
                    .layoutWeight(1)
                  
                  Text('已接收: ' + this.receivedData.length + ' 条')
                    .fontSize(12)
                    .fontColor('#999999')
                    
                  Button('清空')
                    .fontSize(12)
                    .fontColor('#F44336')
                    .backgroundColor(Color.Transparent)
                    .onClick(() => {
                      this.clearReceivedData();
                    })
                }
                
                Column({ space: 8 }) {
                  ForEach(this.receivedData.slice(0, 10), (data: string, index: number) => {
                    Text(data)
                      .fontSize(12)
                      .fontColor('#333333')
                      .width('100%')
                      .padding(8)
                      .backgroundColor(index % 2 === 0 ? '#F9F9F9' : '#FFFFFF')
                      .borderRadius(4)
                  })
                }
                .height(300)
                .border({ width: 1, color: '#E0E0E0' })
                .borderRadius(8)
              }
              .padding(16)
              .backgroundColor('#FFFFFF')
              .borderRadius(12)
              .margin({ left: 16, right: 16 })
            }
          }
          
          // 监控中心视图
          if (this.currentView === 'monitor') {
            Column({ space: 16 }) {
              // 统计卡片
              Grid() {
                GridItem() {
                  this.buildStatCard('在线时长', 
                    Math.floor(this.stats.connectionTime / 3600) + '小时', '#2196F3');
                }
                
                GridItem() {
                  this.buildStatCard('发送数据', 
                    this.stats.totalDataSent + '字节', '#4CAF50');
                }
                
                GridItem() {
                  this.buildStatCard('接收数据', 
                    this.stats.totalDataReceived + '字节', '#FF9800');
                }
                
                GridItem() {
                  this.buildStatCard('成功率', 
                    Math.floor((this.stats.onlineDevices / this.stats.totalDevices) * 100) + '%', '#9C27B0');
                }
              }
              .columnsTemplate('1fr 1fr')
              .rowsTemplate('1fr 1fr')
              .columnsGap(12)
              .rowsGap(12)
              .padding(16)
              .backgroundColor('#FFFFFF')
              .borderRadius(12)
              .margin({ left: 16, right: 16 })
              
              // 系统设置
              Column({ space: 12 }) {
                Row({ space: 8 }) {
                  Text('⚙️')
                    .fontSize(20)
                  
                  Text('系统设置')
                    .fontSize(16)
                    .fontWeight(FontWeight.Medium)
                    .fontColor('#333333')
                }
                
                Row({ space: 12 }) {
                  Text('自动重连')
                    .fontSize(14)
                    .fontColor('#333333')
                    .layoutWeight(1)
                  
                  Toggle({ type: ToggleType.Switch, isOn: this.autoReconnect })
                    .onChange((isOn: boolean) => {
                      this.autoReconnect = isOn;
                    })
                }
                
                Row({ space: 12 }) {
                  Text('服务器地址')
                    .fontSize(14)
                    .fontColor('#333333')
                    .layoutWeight(1)
                  
                  TextInput({ text: this.serverAddress })
                    .width(150)
                    .fontSize(14)
                    .onChange((value: string) => {
                      this.serverAddress = value;
                    })
                }
                
                Row({ space: 12 }) {
                  Text('服务器端口')
                    .fontSize(14)
                    .fontColor('#333333')
                    .layoutWeight(1)
                  
                  TextInput({ text: this.serverPort.toString() })
                    .width(100)
                    .fontSize(14)
                    .inputFilter('^[0-9]*$')
                    .onChange((value: string) => {
                      this.serverPort = parseInt(value) || 8080;
                    })
                }
              }
              .padding(16)
              .backgroundColor('#FFFFFF')
              .borderRadius(12)
              .margin({ left: 16, right: 16 })
            }
          }
        }
      }
      .scrollable(ScrollDirection.Vertical)
      .scrollBar(BarState.Auto)
      .margin({ bottom: 60 })
      
      // 添加设备模态框
      if (this.showAddDevice) {
        this.buildAddDeviceModal();
      }
      
      // 底部操作栏
      Row({ space: 12 }) {
        Button('全部断开')
          .fontSize(14)
          .fontColor('#F44336')
          .backgroundColor('#FFEBEE')
          .layoutWeight(1)
          .height(48)
          .borderRadius(24)
          .onClick(() => {
            this.disconnectAll();
          })
        
        Button('一键检测')
          .fontSize(14)
          .fontColor('#2196F3')
          .backgroundColor('#E3F2FD')
          .layoutWeight(1)
          .height(48)
          .borderRadius(24)
          .onClick(() => {
            this.checkNetworkStatus();
            this.updateDeviceStatus();
          })
      }
      .width('100%')
      .padding(12)
      .backgroundColor('#FFFFFF')
      .border({ top: { width: 1, color: '#E0E0E0' } })
      .position({ x: 0, y: '100%-60' })
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F5F5F5')
  }
  
  // 构建设备卡片
  @Builder
  buildDeviceCard(device: IoTDevice) {
    Row({ space: 12 }) {
      // 选择框
      Checkbox({ name: device.name, group: 'devices' })
        .select(device.isSelected)
        .selectedColor('#2196F3')
        .onChange((selected: boolean) => {
          this.toggleDeviceSelection(device.id);
        })
        .width(24)
        .height(24)
      
      // 设备信息
      Column({ space: 6 }) {
        Row({ space: 8 }) {
          Text(device.name)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
            .fontColor('#333333')
            .layoutWeight(1)
          
          Badge({
            count: device.status === 'online' ? '在线' : 
                   device.status === 'connecting' ? '连接中' : '离线',
            position: BadgePosition.Right,
            color: this.getDeviceStatusColor(device.status)
          })
        }
        
        Row({ space: 12 }) {
          Text(`${device.ipAddress}:${device.port}`)
            .fontSize(12)
            .fontColor('#666666')
          
          Text(device.protocol)
            .fontSize(12)
            .fontColor('#2196F3')
        }
        
        Text(device.lastData || '暂无数据')
          .fontSize(12)
          .fontColor('#999999')
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
      }
      .layoutWeight(1)
      
      // 操作按钮
      Column({ space: 4 }) {
        Button(device.status === 'online' ? '断开' : '连接')
          .fontSize(12)
          .fontColor(device.status === 'online' ? '#F44336' : '#4CAF50')
          .backgroundColor(Color.Transparent)
          .padding({ left: 8, right: 8 })
          .onClick(() => {
            if (device.status === 'online') {
              this.disconnectDevice(device);
            } else {
              this.connectToDevice(device);
            }
          })
        
        Button('删除')
          .fontSize(12)
          .fontColor('#F44336')
          .backgroundColor(Color.Transparent)
          .padding({ left: 8, right: 8 })
          .onClick(() => {
            this.deleteDevice(device.id);
          })
      }
    }
    .width('100%')
    .padding(16)
    .backgroundColor('#FFFFFF')
    .borderRadius(12)
  }
  
  // 构建统计卡片
  @Builder
  buildStatCard(title: string, value: string, color: string) {
    Column({ space: 6 }) {
      Text(value)
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .fontColor(color)
      
      Text(title)
        .fontSize(12)
        .fontColor('#666666')
    }
    .width('100%')
    .padding(12)
    .alignItems(HorizontalAlign.Center)
  }
  
  // 构建添加设备模态框
  @Builder
  buildAddDeviceModal() {
    Column({ space: 16 }) {
      Row({ space: 12 }) {
        Text('添加新设备')
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .fontColor('#333333')
          .layoutWeight(1)
        
        Button('×')
          .fontSize(20)
          .fontColor('#666666')
          .backgroundColor(Color.Transparent)
          .onClick(() => {
            this.showAddDevice = false;
          })
      }
      
      Column({ space: 8 }) {
        Text('设备名称')
          .fontSize(14)
          .fontColor('#666666')
        
        TextInput({ text: this.newDevice.name })
          .width('100%')
          .fontSize(16)
          .backgroundColor('#F5F5F5')
          .onChange((value: string) => {
            this.newDevice.name = value;
          })
      }
      
      Row({ space: 12 }) {
        Column({ space: 8 }) {
          Text('IP地址')
            .fontSize(14)
            .fontColor('#666666')
          
          TextInput({ text: this.newDevice.ipAddress })
            .width('100%')
            .fontSize(16)
            .backgroundColor('#F5F5F5')
            .onChange((value: string) => {
              this.newDevice.ipAddress = value;
            })
        }
        
        Column({ space: 8 }) {
          Text('端口')
            .fontSize(14)
            .fontColor('#666666')
          
          TextInput({ text: this.newDevice.port.toString() })
            .width('100%')
            .fontSize(16)
            .backgroundColor('#F5F5F5')
            .inputFilter('^[0-9]*$')
            .onChange((value: string) => {
              this.newDevice.port = parseInt(value) || 0;
            })
        }
      }
      
      Column({ space: 8 }) {
        Text('通信协议')
          .fontSize(14)
          .fontColor('#666666')
        
        Row({ space: 8 }) {
          ForEach(['TCP', 'UDP', 'MQTT', 'HTTP'], (protocol: string) => {
            Button(protocol)
              .fontSize(12)
              .fontColor(this.newDevice.protocol === protocol ? '#FFFFFF' : '#2196F3')
              .backgroundColor(this.newDevice.protocol === protocol ? '#2196F3' : '#E3F2FD')
              .padding({ left: 12, right: 12, top: 6, bottom: 6 })
              .borderRadius(16)
              .onClick(() => {
                this.newDevice.protocol = protocol;
              })
          })
        }
      }
      
      Button('添加设备')
        .fontSize(16)
        .fontWeight(FontWeight.Medium)
        .fontColor('#FFFFFF')
        .backgroundColor('#2196F3')
        .width('100%')
        .height(48)
        .borderRadius(24)
        .onClick(() => {
          this.addNewDevice();
        })
    }
    .width('85%')
    .padding(20)
    .backgroundColor('#FFFFFF')
    .borderRadius(16)
    .position({ x: '7.5%', y: this.screenHeight * 0.15 })
    .zIndex(100)
    .shadow({ radius: 20, color: '#00000020', offsetX: 0, offsetY: 4 })
  }
}

想入门鸿蒙开发又怕花冤枉钱?别错过!现在能免费系统学 -- 从 ArkTS 面向对象核心的类和对象、继承多态,到吃透鸿蒙开发关键技能,还能冲刺鸿蒙基础 +高级开发者证书,更惊喜的是考证成功还送好礼!快加入我的鸿蒙班,一起从入门到精通,班级链接:点击https://developer.huawei.com/consumer/cn/training/classDetail/b7365031334e4353a9a0fd6785bb0791?type=1?ha_source=hmosclass&ha_sourceId=89000248免费进入
 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐