在这里插入图片描述

每日一句正能量

少与人争,才能宠辱不惊,闲看庭前花开花落,少与己争,方可去留无意,漫随天外云卷云舒。
不与人争辩对错高下,外界的毁誉就伤不到你;不与自己较劲、不苛责过去的决定,内心的波动就会平息。

一、前言:当AI管家常驻屏幕边缘

在万物互联的时代,智能家居已经成为现代生活的重要组成部分。然而,传统的智能家居控制方式往往存在诸多不便:需要打开特定的APP、在不同设备间频繁切换、无法感知用户的实时需求。当双手沾满面粉时想调节厨房灯光亮度,当抱着婴儿时想关闭卧室窗帘——这些场景下,传统的触控操作显得笨拙而低效。

HarmonyOS 6(API 23)带来的悬浮导航(Floating Navigation)沉浸光感(Immersive Lighting)能力,让我们有机会打造一个常驻屏幕边缘的AI智能管家——它像一位贴心的家庭管家,在你需要时随时唤出,通过语音、手势甚至环境感知自动执行控制;它通过光效反馈家居状态,让你无需看屏幕就能感知家中一切。

核心创新点:

  • 🏠 全屋设备悬浮掌控:悬浮窗常驻显示核心家居状态,支持跨场景快速控制
  • 💡 环境状态光感:通过设备边框光效颜色变化,反映家中环境状态(温度/安防/能耗)
  • 🤖 情境感知智能体:自动识别用户场景(回家/离家/睡眠/观影),主动推荐控制方案
  • 🎙️ 多模态交互:语音控制 + 手势操作 + 环境感知,解放双手

二、应用场景设计

2.1 场景一:烹饪助手模式

用户在厨房做饭,双手沾满油污。通过语音"把厨房灯调亮一点",悬浮窗AI智能体识别指令,自动调节灯光亮度,同时边框泛起温暖的橙色光效,表示"烹饪模式"已激活。

2.2 场景二:安防状态感知

深夜家中门窗传感器被触发,设备四周边框立即泛起红色脉冲光效,悬浮窗自动展开显示安防摄像头画面和异常位置,同时智能体分析是否为误报(宠物/风吹)。

2.3 场景三:能耗优化建议

AI智能体持续学习用户用电习惯,在悬浮窗中推送"检测到您每天18:00-20:00空调设定温度过低,建议调整为26℃可节省15%电费",边框泛起绿色光效表示"节能建议"。

三、技术架构

┌─────────────────────────────────────────────────────────────┐
│         HarmonyOS Smart Home Control Center Agent           │
├─────────────┬─────────────┬─────────────┬───────────────────┤
│  悬浮窗UI   │  沉浸光感   │  智能体引擎  │   设备接入模块     │
│  FloatUI    │  Lighting   │  AI Engine  │   DeviceConnector │
├─────────────┴─────────────┴─────────────┴───────────────────┤
│                    情境感知层(Context Aware)                 │
│   位置感知 │ 时间分析 │ 环境检测 │ 用户习惯 │ 语音理解        │
├─────────────────────────────────────────────────────────────┤
│              HarmonyOS 6 (API 23) 系统服务层                 │
│   悬浮导航 │ 光感服务 │ 智能体框架 │ 分布式设备 │ 语音服务      │
└─────────────────────────────────────────────────────────────┘

四、核心代码实现

4.1 家居设备上下文感知引擎(HomeContextEngine)

这是整个系统的"感官",通过分布式设备服务实时接入全屋智能设备,分析家居环境状态。

// engine/HomeContextEngine.ets
import { deviceManager } from '@kit.DistributedServiceKit';
import { sensor } from '@kit.SensorServiceKit';
import { BusinessError } from '@kit.BasicServicesKit';

export interface HomeContext {
  location: UserLocation;           // 用户当前位置
  timeContext: TimeContext;         // 时间上下文
  environment: EnvironmentState;    // 环境状态
  activeDevices: SmartDevice[];     // 活跃设备列表
  securityStatus: SecurityLevel;    // 安防级别
  energyStatus: EnergyStatus;       // 能耗状态
  scenePrediction: PredictedScene;  // 场景预测
}

export enum UserLocation {
  HOME = 'home',
  LIVING_ROOM = 'living_room',
  BEDROOM = 'bedroom',
  KITCHEN = 'kitchen',
  BATHROOM = 'bathroom',
  AWAY = 'away'
}

export interface TimeContext {
  hour: number;
  isWeekend: boolean;
  isHoliday: boolean;
  season: 'spring' | 'summer' | 'autumn' | 'winter';
  dayPhase: 'dawn' | 'morning' | 'afternoon' | 'evening' | 'night' | 'midnight';
}

export interface EnvironmentState {
  temperature: number;      // 温度
  humidity: number;         // 湿度
  illuminance: number;      // 光照度
  airQuality: number;       // 空气质量指数
  noiseLevel: number;       // 噪音分贝
}

export enum SecurityLevel {
  SAFE = 'safe',           // 安全:绿色
  CAUTION = 'caution',     // 注意:黄色
  ALERT = 'alert',         // 警戒:橙色
  EMERGENCY = 'emergency'  // 紧急:红色
}

export interface EnergyStatus {
  currentPower: number;     // 当前功率(W)
  dailyUsage: number;       // 今日用电量(kWh)
  monthlyUsage: number;     // 本月用电量(kWh)
  estimatedCost: number;    // 预估电费
  efficiency: number;       // 能效等级 0-100
}

export interface PredictedScene {
  scene: string;            // 预测场景
  confidence: number;       // 置信度
  triggerTime: number;      // 预计触发时间
  suggestedActions: ActionSuggestion[];
}

export interface ActionSuggestion {
  deviceId: string;
  action: string;
  value: any;
  reason: string;
}

export interface SmartDevice {
  id: string;
  name: string;
  type: DeviceType;
  location: string;
  status: DeviceStatus;
  isOnline: boolean;
  lastActive: number;
}

export enum DeviceType {
  LIGHT = 'light',
  AC = 'air_conditioner',
  CURTAIN = 'curtain',
  CAMERA = 'camera',
  LOCK = 'smart_lock',
  SENSOR = 'sensor',
  SWITCH = 'switch',
  SPEAKER = 'speaker'
}

export interface DeviceStatus {
  power: 'on' | 'off';
  brightness?: number;
  temperature?: number;
  mode?: string;
  locked?: boolean;
}

export class HomeContextEngine {
  private deviceManager: deviceManager.DeviceManager | null = null;
  private sensorManager: sensor.SensorManager | null = null;
  private contextCallbacks: Array<(context: HomeContext) => void> = [];
  private currentContext: HomeContext | null = null;
  private updateInterval: number = 0;
  private deviceCache: Map<string, SmartDevice> = new Map();

  /**
   * 初始化家居上下文感知
   * 亮点:通过分布式设备管理接入全屋设备,支持跨设备协同
   */
  async init(): Promise<void> {
    try {
      // 初始化设备管理器
      this.deviceManager = await deviceManager.createDeviceManager({
        bundleName: getContext(this).applicationInfo.name
      });

      // 注册设备状态变更监听
      this.deviceManager.on('deviceStateChange', (event) => {
        this.handleDeviceChange(event);
      });

      // 初始化传感器管理器
      this.sensorManager = sensor.getSensorManager();

      // 启动定时刷新(每10秒)
      this.updateInterval = setInterval(() => this.refreshContext(), 10000);

      // 首次上下文构建
      await this.refreshContext();

      console.info('[HomeContext] 家居上下文感知引擎初始化完成');
    } catch (err) {
      console.error(`[HomeContext] 初始化失败: ${JSON.stringify(err)}`);
    }
  }

  /**
   * 刷新家居上下文
   */
  private async refreshContext(): Promise<void> {
    try {
      // 获取用户位置
      const location = await this.detectUserLocation();
      
      // 获取时间上下文
      const timeContext = this.buildTimeContext();
      
      // 获取环境状态
      const environment = await this.readEnvironmentSensors();
      
      // 获取设备状态
      const devices = await this.queryAllDevices();
      
      // 分析安防状态
      const security = this.analyzeSecurityStatus(devices);
      
      // 分析能耗状态
      const energy = this.calculateEnergyStatus(devices);
      
      // 预测场景
      const prediction = this.predictScene(location, timeContext, devices);

      const context: HomeContext = {
        location,
        timeContext,
        environment,
        activeDevices: devices.filter(d => d.status.power === 'on'),
        securityStatus: security,
        energyStatus: energy,
        scenePrediction: prediction
      };

      this.currentContext = context;
      
      // 通知订阅者
      this.contextCallbacks.forEach(cb => cb(context));

    } catch (err) {
      console.error(`[HomeContext] 刷新失败: ${JSON.stringify(err)}`);
    }
  }

  /**
   * 检测用户位置
   * 策略:多源融合(GPS + WiFi指纹 + 设备使用习惯)
   */
  private async detectUserLocation(): Promise<<UserLocation> {
    // 简化实现,实际应融合多源数据
    const hour = new Date().getHours();
    
    if (hour >= 7 && hour <= 9) return UserLocation.KITCHEN;
    if (hour >= 19 && hour <= 23) return UserLocation.LIVING_ROOM;
    if (hour >= 23 || hour <= 7) return UserLocation.BEDROOM;
    
    return UserLocation.HOME;
  }

  /**
   * 构建时间上下文
   */
  private buildTimeContext(): TimeContext {
    const now = new Date();
    const hour = now.getHours();
    
    let dayPhase: TimeContext['dayPhase'] = 'morning';
    if (hour >= 5 && hour < 8) dayPhase = 'dawn';
    else if (hour >= 8 && hour < 12) dayPhase = 'morning';
    else if (hour >= 12 && hour < 14) dayPhase = 'afternoon';
    else if (hour >= 14 && hour < 18) dayPhase = 'afternoon';
    else if (hour >= 18 && hour < 22) dayPhase = 'evening';
    else if (hour >= 22 && hour < 24) dayPhase = 'night';
    else dayPhase = 'midnight';

    const month = now.getMonth();
    let season: TimeContext['season'] = 'spring';
    if (month >= 3 && month <= 5) season = 'spring';
    else if (month >= 6 && month <= 8) season = 'summer';
    else if (month >= 9 && month <= 11) season = 'autumn';
    else season = 'winter';

    return {
      hour,
      isWeekend: now.getDay() === 0 || now.getDay() === 6,
      isHoliday: false, // 实际应查询节假日API
      season,
      dayPhase
    };
  }

  /**
   * 读取环境传感器
   */
  private async readEnvironmentSensors(): Promise<<EnvironmentState> {
    try {
      // 读取温度湿度传感器
      const thSensor = await this.sensorManager?.getSingleSensor(
        sensor.SensorId.SENSOR_TYPE_AMBIENT_TEMPERATURE
      );
      
      // 读取光照传感器
      const lightSensor = await this.sensorManager?.getSingleSensor(
        sensor.SensorId.SENSOR_TYPE_AMBIENT_LIGHT
      );

      return {
        temperature: thSensor?.temperature || 24,
        humidity: thSensor?.humidity || 50,
        illuminance: lightSensor?.intensity || 300,
        airQuality: 85, // 模拟数据
        noiseLevel: 45  // 模拟数据
      };
    } catch (err) {
      // 传感器不可用,返回默认值
      return {
        temperature: 24,
        humidity: 50,
        illuminance: 300,
        airQuality: 85,
        noiseLevel: 45
      };
    }
  }

  /**
   * 查询所有设备状态
   */
  private async queryAllDevices(): Promise<<SmartDevice[]> {
    if (!this.deviceManager) return [];

    try {
      const deviceList = await this.deviceManager.getTrustedDeviceListSync();
      const devices: SmartDevice[] = [];

      for (const deviceInfo of deviceList) {
        const device = await this.queryDeviceStatus(deviceInfo.deviceId);
        if (device) {
          this.deviceCache.set(device.id, device);
          devices.push(device);
        }
      }

      return devices;
    } catch (err) {
      // 返回缓存数据
      return Array.from(this.deviceCache.values());
    }
  }

  /**
   * 查询单个设备状态
   */
  private async queryDeviceStatus(deviceId: string): Promise<<SmartDevice | null> {
    // 实际应通过分布式通信查询设备状态
    // 简化实现
    const mockDevices: Record<string, SmartDevice> = {
      'light_001': {
        id: 'light_001',
        name: '客厅主灯',
        type: DeviceType.LIGHT,
        location: 'living_room',
        status: { power: 'on', brightness: 80 },
        isOnline: true,
        lastActive: Date.now()
      },
      'ac_001': {
        id: 'ac_001',
        name: '主卧空调',
        type: DeviceType.AC,
        location: 'bedroom',
        status: { power: 'on', temperature: 26, mode: 'cool' },
        isOnline: true,
        lastActive: Date.now()
      },
      'camera_001': {
        id: 'camera_001',
        name: '门口摄像头',
        type: DeviceType.CAMERA,
        location: 'entrance',
        status: { power: 'on' },
        isOnline: true,
        lastActive: Date.now()
      }
    };

    return mockDevices[deviceId] || null;
  }

  /**
   * 分析安防状态
   */
  private analyzeSecurityStatus(devices: SmartDevice[]): SecurityLevel {
    const sensors = devices.filter(d => d.type === DeviceType.SENSOR);
    
    // 检查门窗传感器
    const doorSensors = sensors.filter(s => s.location.includes('door') || s.location.includes('window'));
    const triggeredSensors = doorSensors.filter(s => s.status.power === 'on' && this.isSensorTriggered(s));
    
    if (triggeredSensors.length > 0) {
      const hour = new Date().getHours();
      // 深夜触发更紧急
      if (hour >= 23 || hour <= 6) return SecurityLevel.EMERGENCY;
      return SecurityLevel.ALERT;
    }

    // 检查摄像头异常
    const cameras = devices.filter(d => d.type === DeviceType.CAMERA);
    const offlineCameras = cameras.filter(c => !c.isOnline);
    if (offlineCameras.length > 0) return SecurityLevel.CAUTION;

    return SecurityLevel.SAFE;
  }

  private isSensorTriggered(sensor: SmartDevice): boolean {
    // 简化:假设传感器有triggered字段
    return (sensor.status as any).triggered === true;
  }

  /**
   * 计算能耗状态
   */
  private calculateEnergyStatus(devices: SmartDevice[]): EnergyStatus {
    const activeDevices = devices.filter(d => d.status.power === 'on');
    
    // 估算功率
    const powerMap: Record<string, number> = {
      'light': 15,
      'air_conditioner': 1500,
      'curtain': 50,
      'camera': 10,
      'smart_lock': 5,
      'speaker': 20
    };

    const currentPower = activeDevices.reduce((sum, d) => {
      return sum + (powerMap[d.type] || 50);
    }, 0);

    // 模拟日用电量和月用电量
    const dailyUsage = currentPower * 8 / 1000; // 假设8小时
    const monthlyUsage = dailyUsage * 30;

    return {
      currentPower,
      dailyUsage,
      monthlyUsage,
      estimatedCost: monthlyUsage * 0.6, // 假设0.6元/度
      efficiency: Math.max(100 - (currentPower / 3000) * 100, 0)
    };
  }

  /**
   * 场景预测
   * 基于时间、位置、历史习惯预测用户下一步行为
   */
  private predictScene(location: UserLocation, time: TimeContext, devices: SmartDevice[]): PredictedScene {
    const suggestions: ActionSuggestion[] = [];
    let scene = 'normal';
    let confidence = 0.5;

    // 回家场景
    if (location === UserLocation.HOME && time.hour >= 18 && time.dayPhase === 'evening') {
      scene = 'home_return';
      confidence = 0.85;
      suggestions.push(
        { deviceId: 'light_001', action: 'turn_on', value: { brightness: 80 }, reason: '傍晚回家,自动开灯' },
        { deviceId: 'ac_001', action: 'set_temperature', value: 26, reason: '提前调节室温' }
      );
    }

    // 睡眠场景
    if (location === UserLocation.BEDROOM && time.hour >= 22) {
      scene = 'sleep';
      confidence = 0.9;
      suggestions.push(
        { deviceId: 'light_001', action: 'turn_off', value: null, reason: '准备入睡,关闭灯光' },
        { deviceId: 'ac_001', action: 'set_temperature', value: 27, reason: '睡眠模式,节能舒适' }
      );
    }

    // 观影场景
    if (location === UserLocation.LIVING_ROOM && time.hour >= 20 && time.dayPhase === 'evening') {
      scene = 'movie';
      confidence = 0.6;
      suggestions.push(
        { deviceId: 'light_001', action: 'set_brightness', value: 20, reason: '观影模式,降低亮度' },
        { deviceId: 'curtain_001', action: 'close', value: null, reason: '关闭窗帘,提升观影体验' }
      );
    }

    return {
      scene,
      confidence,
      triggerTime: Date.now() + 300000, // 5分钟后
      suggestedActions: suggestions
    };
  }

  /**
   * 执行设备控制
   */
  async controlDevice(deviceId: string, action: string, value?: any): Promise<<boolean> {
    try {
      // 实际应通过分布式通信发送控制指令
      console.info(`[HomeContext] 控制设备: ${deviceId}, 动作: ${action}, 值: ${value}`);
      
      // 更新本地缓存
      const device = this.deviceCache.get(deviceId);
      if (device) {
        if (action === 'turn_on') device.status.power = 'on';
        if (action === 'turn_off') device.status.power = 'off';
        if (action === 'set_brightness') device.status.brightness = value;
        if (action === 'set_temperature') device.status.temperature = value;
      }
      
      return true;
    } catch (err) {
      console.error(`[HomeContext] 控制失败: ${JSON.stringify(err)}`);
      return false;
    }
  }

  onContextChange(callback: (context: HomeContext) => void): void {
    this.contextCallbacks.push(callback);
  }

  getCurrentContext(): HomeContext | null {
    return this.currentContext;
  }

  private handleDeviceChange(event: deviceManager.DeviceStateChangeEvent): void {
    // 设备状态变更时刷新上下文
    this.refreshContext();
  }

  destroy(): void {
    clearInterval(this.updateInterval);
    this.deviceManager?.off('deviceStateChange');
  }
}

4.2 沉浸光感家居状态反馈(HomeLightingController)

光效是家居状态的"环境化延伸",让用户无需看屏幕就能感知家中状态。

// lighting/HomeLightingController.ets
import { lighting } from '@kit.ArkUI';
import { SecurityLevel, EnergyStatus, EnvironmentState, TimeContext } from '../engine/HomeContextEngine';

export class HomeLightingController {
  private currentMode: string = 'normal';
  private isNightMode: boolean = false;

  /**
   * 初始化家居光感
   * 设计哲学:光效应成为家居状态的"环境氛围"
   */
  async init(): Promise<void> {
    if (!lighting.isImmersiveLightSupported()) {
      console.warn('[HomeLight] 设备不支持沉浸光感');
      return;
    }

    // 初始状态:柔和白色
    await this.setLightEffect({
      type: 'solid',
      position: 'bottom_edge',
      color: '#E0E0E0',
      brightness: 20,
      duration: 0
    });

    console.info('[HomeLight] 家居光感初始化完成');
  }

  /**
   * 根据家居状态更新光效
   */
  async updateByContext(context: {
    security: SecurityLevel;
    energy: EnergyStatus;
    environment: EnvironmentState;
    time: TimeContext;
    location: string;
  }): Promise<void> {
    // 优先级:安防 > 能耗 > 环境舒适 > 时间氛围

    // 安防状态最高优先级
    if (context.security !== SecurityLevel.SAFE) {
      await this.setSecurityLighting(context.security);
      return;
    }

    // 能耗异常
    if (context.energy.efficiency < 50) {
      await this.setEnergyAlert(context.energy);
      return;
    }

    // 环境不适
    if (context.environment.temperature > 30 || context.environment.temperature < 16) {
      await this.setEnvironmentAlert(context.environment);
      return;
    }

    // 正常状态:根据时间和位置营造氛围
    await this.setAmbientLighting(context.time, context.location);
  }

  /**
   * 安防状态光效
   */
  private async setSecurityLighting(level: SecurityLevel): Promise<void> {
    const effects: Record<<SecurityLevel, lighting.LightEffect> = {
      [SecurityLevel.SAFE]: {
        type: 'solid',
        position: 'bottom_edge',
        color: '#00E676',
        brightness: 20,
        duration: 0
      },
      [SecurityLevel.CAUTION]: {
        type: 'breathing',
        position: 'bottom_edge',
        color: '#FFD600',
        brightness: 40,
        duration: 0,
        frequency: 2000
      },
      [SecurityLevel.ALERT]: {
        type: 'flashing',
        position: 'all_edges',
        color: '#FF9100',
        brightness: 60,
        duration: 0,
        flashCount: -1,
        frequency: 1000
      },
      [SecurityLevel.EMERGENCY]: {
        type: 'flashing',
        position: 'all_edges',
        color: '#FF1744',
        brightness: 80,
        duration: 0,
        flashCount: -1,
        frequency: 500
      }
    };

    await lighting.setImmersiveLight(effects[level]);
    console.info(`[HomeLight] 安防光效: ${level}`);
  }

  /**
   * 能耗告警光效
   */
  private async setEnergyAlert(energy: EnergyStatus): Promise<void> {
    await lighting.setImmersiveLight({
      type: 'wave',
      position: 'all_edges',
      color: '#FF9100',
      brightness: 50,
      duration: 0,
      direction: 'clockwise',
      speed: 'slow'
    });
  }

  /**
   * 环境异常光效
   */
  private async setEnvironmentAlert(env: EnvironmentState): Promise<void> {
    const isHot = env.temperature > 30;
    
    await lighting.setImmersiveLight({
      type: 'breathing',
      position: 'all_edges',
      color: isHot ? '#FF5722' : '#2196F3',  // 热=红橙,冷=蓝
      brightness: 45,
      duration: 0,
      frequency: 2500
    });
  }

  /**
   * 氛围光效
   * 根据时间和位置营造舒适氛围
   */
  private async setAmbientLighting(time: TimeContext, location: string): Promise<void> {
    const isNight = time.dayPhase === 'night' || time.dayPhase === 'midnight';
    this.isNightMode = isNight;

    // 深夜模式:极暗,不影响睡眠
    if (time.dayPhase === 'midnight') {
      await lighting.setImmersiveLight({
        type: 'solid',
        position: 'bottom_edge',
        color: '#1A237E',  // 深蓝
        brightness: 5,
        duration: 0
      });
      return;
    }

    // 根据位置设置不同氛围
    const locationColors: Record<string, string> = {
      'living_room': isNight ? '#FF6F00' : '#FFE0B2',  // 客厅:暖橙
      'bedroom': isNight ? '#4A148C' : '#E1BEE7',      // 卧室:柔和紫
      'kitchen': '#FFF3E0',                              // 厨房:暖白
      'bathroom': '#E0F7FA'                              // 浴室:清新蓝
    };

    const color = locationColors[location] || '#E0E0E0';
    const brightness = isNight ? 15 : 25;

    await lighting.setImmersiveLight({
      type: 'solid',
      position: 'bottom_edge',
      color: color,
      brightness: brightness,
      duration: 0
    });
  }

  /**
   * 执行控制时的反馈光效
   */
  async controlFeedback(success: boolean): Promise<void> {
    await lighting.setImmersiveLight({
      type: 'flashing',
      position: 'bottom_edge',
      color: success ? '#00E676' : '#FF1744',
      brightness: 40,
      duration: 500,
      flashCount: 1
    });
  }

  /**
   * 场景切换动画
   */
  async sceneTransition(sceneName: string): Promise<void> {
    const sceneColors: Record<string, string> = {
      'home_return': '#FF9800',   // 回家:温暖橙
      'sleep': '#3F51B5',         // 睡眠:静谧蓝
      'movie': '#212121',         // 观影:深黑
      'party': '#E91E63',         // 聚会:活力粉
      'reading': '#FFEB3B'        // 阅读:明亮黄
    };

    const color = sceneColors[sceneName] || '#E0E0E0';

    // 渐变过渡
    await lighting.setImmersiveLight({
      type: 'solid',
      position: 'all_edges',
      color: color,
      brightness: 30,
      duration: 1000
    });

    await new Promise(resolve => setTimeout(resolve, 1000));

    // 恢复氛围
    // 实际应恢复之前的状态...
  }

  async reset(): Promise<void> {
    await lighting.resetImmersiveLight();
  }
}

4.3 家居智能体引擎(HomeAgentEngine)

这是系统的"智能管家大脑",负责理解用户意图、生成控制策略、提供生活建议。

// agent/HomeAgentEngine.ets
import { ai } from '@kit.AiKit';
import { HomeContext, SmartDevice, ActionSuggestion, UserLocation, TimeContext } from '../engine/HomeContextEngine';

export interface HomeResponse {
  type: 'control' | 'query' | 'suggestion' | 'alert';
  message: string;
  actions?: ActionSuggestion[];
  data?: any;
  confidence: number;
}

export class HomeAgentEngine {
  private agent: ai.AgentSession | null = null;
  private userHabits: Map<string, any> = new Map();  // 用户习惯学习
  private commandHistory: string[] = [];  // 指令历史

  /**
   * 初始化家居智能体
   * 加载家居控制知识库
   */
  async init(): Promise<void> {
    const model = await ai.createModel({
      modelId: 'harmonyos-home-agent-v1',
      type: ai.ModelType.LOCAL,
      capabilities: ['nlp', 'intent_recognition', 'home_automation']
    });

    this.agent = await ai.createAgentSession({
      model: model,
      systemPrompt: `你是一位专业的智能家居管家,精通HarmonyOS全屋智能系统。
        请基于用户指令和当前家居状态,提供:
        1. 精确的设备控制指令
        2. 场景化的智能建议
        3. 能耗优化方案
        4. 安防状态提醒
        
        控制指令格式:
        - 开/关:{ "deviceId": "xxx", "action": "turn_on/off" }
        - 调节:{ "deviceId": "xxx", "action": "set_xxx", "value": xxx }
        
        回答要求:
        - 用自然语言解释执行的操作
        - 提供执行原因
        - 给出相关建议`
    });

    console.info('[HomeAgent] 家居智能体初始化完成');
  }

  /**
   * 处理自然语言指令
   */
  async processCommand(command: string, context: HomeContext): Promise<<HomeResponse> {
    if (!this.agent) return { type: 'query', message: '智能体未初始化', confidence: 0 };

    this.commandHistory.push(command);

    // 意图识别
    const intent = await this.recognizeIntent(command);
    
    switch (intent.type) {
      case 'control':
        return await this.handleControlIntent(intent, context);
      case 'query':
        return await this.handleQueryIntent(intent, context);
      case 'scene':
        return await this.handleSceneIntent(intent, context);
      default:
        return await this.handleGeneralQuery(command, context);
    }
  }

  /**
   * 识别用户意图
   */
  private async recognizeIntent(command: string): Promise<<{ type: string; entities: any }> {
    const prompt = `分析用户指令的意图和实体:
      指令:"${command}"
      
      请输出JSON格式:
      {
        "type": "control|query|scene|general",
        "entities": {
          "device": "设备名称或类型",
          "action": "动作",
          "value": "数值",
          "location": "位置"
        }
      }`;

    const result = await this.agent!.invoke({
      input: { question: prompt },
      options: { maxTokens: 256, temperature: 0.1 }
    });

    return JSON.parse(result.data?.intent || '{"type":"general","entities":{}}');
  }

  /**
   * 处理控制意图
   */
  private async handleControlIntent(intent: any, context: HomeContext): Promise<<HomeResponse> {
    const { device, action, value, location } = intent.entities;
    
    // 查找目标设备
    let targetDevice: SmartDevice | undefined;
    
    if (device) {
      targetDevice = context.activeDevices.find(d => 
        d.name.includes(device) || d.type === device
      );
    }
    
    if (location && !targetDevice) {
      targetDevice = context.activeDevices.find(d => d.location === location);
    }

    if (!targetDevice) {
      return {
        type: 'query',
        message: `未找到${device || location}对应的设备,请检查设备名称`,
        confidence: 0.3
      };
    }

    // 生成控制动作
    const controlAction: ActionSuggestion = {
      deviceId: targetDevice.id,
      action: this.mapAction(action),
      value: this.parseValue(value, action),
      reason: `根据您的指令"${intent.original}"执行`
    };

    return {
      type: 'control',
      message: `已为您${action}${targetDevice.name}${value ? '到' + value : ''}`,
      actions: [controlAction],
      confidence: 0.9
    };
  }

  /**
   * 处理查询意图
   */
  private async handleQueryIntent(intent: any, context: HomeContext): Promise<<HomeResponse> {
    const { device, location } = intent.entities;

    if (intent.entities.queryType === 'temperature') {
      return {
        type: 'query',
        message: `当前室内温度${context.environment.temperature}℃,湿度${context.environment.humidity}%,${context.environment.temperature > 28 ? '建议开启空调' : '体感舒适'}`,
        data: context.environment,
        confidence: 0.95
      };
    }

    if (intent.entities.queryType === 'security') {
      const status = context.securityStatus === 'safe' ? '安全' : 
                     context.securityStatus === 'caution' ? '需注意' :
                     context.securityStatus === 'alert' ? '警戒中' : '紧急';
      return {
        type: 'query',
        message: `家中安防状态:${status}${context.securityStatus !== 'safe' ? '请立即查看详情' : '一切正常'}`,
        data: { security: context.securityStatus },
        confidence: 0.95
      };
    }

    if (intent.entities.queryType === 'energy') {
      return {
        type: 'query',
        message: `今日用电${context.energyStatus.dailyUsage.toFixed(1)}度,预估电费${context.energyStatus.estimatedCost.toFixed(1)}元。能效等级${context.energyStatus.efficiency > 80 ? '优秀' : context.energyStatus.efficiency > 60 ? '良好' : '需优化'}`,
        data: context.energyStatus,
        confidence: 0.9
      };
    }

    return {
      type: 'query',
      message: '我可以帮您查询温度、安防、能耗等状态,请问您想了解什么?',
      confidence: 0.5
    };
  }

  /**
   * 处理场景意图
   */
  private async handleSceneIntent(intent: any, context: HomeContext): Promise<<HomeResponse> {
    const sceneName = intent.entities.scene;
    
    const sceneActions: Record<string, ActionSuggestion[]> = {
      'home': [
        { deviceId: 'light_001', action: 'turn_on', value: { brightness: 80 }, reason: '回家模式:欢迎回家' },
        { deviceId: 'ac_001', action: 'set_temperature', value: 26, reason: '调节舒适温度' }
      ],
      'sleep': [
        { deviceId: 'light_001', action: 'turn_off', value: null, reason: '睡眠模式:晚安' },
        { deviceId: 'ac_001', action: 'set_temperature', value: 27, reason: '睡眠温度' },
        { deviceId: 'curtain_001', action: 'close', value: null, reason: '关闭窗帘' }
      ],
      'movie': [
        { deviceId: 'light_001', action: 'set_brightness', value: 20, reason: '观影模式' },
        { deviceId: 'curtain_001', action: 'close', value: null, reason: '关闭窗帘' }
      ],
      'away': [
        { deviceId: 'light_001', action: 'turn_off', value: null, reason: '离家模式:节能' },
        { deviceId: 'ac_001', action: 'turn_off', value: null, reason: '关闭空调' },
        { deviceId: 'camera_001', action: 'turn_on', value: null, reason: '开启安防' }
      ]
    };

    const actions = sceneActions[sceneName] || [];

    return {
      type: 'control',
      message: `已切换到${sceneName}模式,${actions.length}个设备已调整`,
      actions,
      confidence: 0.95
    };
  }

  /**
   * 处理一般查询
   */
  private async handleGeneralQuery(command: string, context: HomeContext): Promise<<HomeResponse> {
    const prompt = `用户问题:${command}
      
      当前家居状态:
      - 位置:${context.location}
      - 时间:${context.timeContext.dayPhase}
      - 温度:${context.environment.temperature}℃
      - 安防:${context.securityStatus}
      - 能耗:${context.energyStatus.dailyUsage}度/天
      
      请给出有帮助的回答。`;

    const result = await this.agent!.invoke({
      input: { question: prompt },
      options: { maxTokens: 512, temperature: 0.5 }
    });

    return {
      type: 'query',
      message: result.data?.answer || '抱歉,我没有理解您的问题',
      confidence: 0.6
    };
  }

  /**
   * 主动建议
   * 基于上下文主动推送建议
   */
  async generateProactiveSuggestions(context: HomeContext): Promise<<HomeResponse[]> {
    const suggestions: HomeResponse[] = [];

    // 能耗建议
    if (context.energyStatus.efficiency < 60) {
      suggestions.push({
        type: 'suggestion',
        message: `检测到能耗较高,建议将空调温度调高1℃可节省约8%电费`,
        actions: [{ deviceId: 'ac_001', action: 'set_temperature', value: (context.activeDevices.find(d => d.id === 'ac_001')?.status.temperature || 26) + 1, reason: '节能建议' }],
        confidence: 0.8
      });
    }

    // 安防建议
    if (context.securityStatus === 'safe' && context.timeContext.hour >= 23) {
      suggestions.push({
        type: 'suggestion',
        message: '夜深了,建议开启夜间安防模式',
        actions: [{ deviceId: 'camera_001', action: 'turn_on', value: { mode: 'night' }, reason: '夜间安防' }],
        confidence: 0.7
      });
    }

    // 舒适建议
    if (context.environment.temperature > 30 && context.timeContext.season === 'summer') {
      suggestions.push({
        type: 'suggestion',
        message: `室内温度较高(${context.environment.temperature}℃),建议开启空调或调整窗帘`,
        actions: [
          { deviceId: 'ac_001', action: 'turn_on', value: { temperature: 26 }, reason: '降温' },
          { deviceId: 'curtain_001', action: 'close', value: null, reason: '遮阳' }
        ],
        confidence: 0.85
      });
    }

    return suggestions;
  }

  private mapAction(action: string): string {
    const map: Record<string, string> = {
      '开': 'turn_on',
      '关': 'turn_off',
      '打开': 'turn_on',
      '关闭': 'turn_off',
      '调亮': 'set_brightness',
      '调暗': 'set_brightness',
      '调高': 'set_temperature',
      '调低': 'set_temperature'
    };
    return map[action] || action;
  }

  private parseValue(value: string, action: string): any {
    if (!value) return null;
    
    const numMatch = value.match(/\d+/);
    if (numMatch) {
      const num = parseInt(numMatch[0]);
      if (action.includes('brightness')) return num;
      if (action.includes('temperature')) return num;
      return num;
    }
    
    return value;
  }

  destroy(): void {
    this.agent?.destroy();
  }
}

4.4 悬浮窗家居控制面板(HomeFloatWindow)

// float/HomeFloatWindow.ets
import { window } from '@kit.ArkUI';
import { emitter } from '@kit.BasicServicesKit';
import { HomeContext, SmartDevice } from '../engine/HomeContextEngine';
import { HomeResponse } from '../agent/HomeAgentEngine';

export class HomeFloatWindow {
  private floatWin: window.Window | null = null;
  private currentLevel: 'capsule' | 'panel' = 'capsule';

  async create(): Promise<void> {
    const option: window.WindowOption = {
      name: 'SmartHomeHub',
      windowType: window.WindowType.TYPE_FLOAT,
      ctx: getContext(this)
    };

    this.floatWin = await window.createWindow(getContext(this), option);
    
    // 胶囊形态:显示核心状态
    await this.floatWin.resize({ width: 100, height: 100 });
    await this.floatWin.moveWindowTo({ x: 950, y: 150 });
    await this.floatWin.setWindowTouchable(true);
    await this.floatWin.setUIContent('pages/HomeCapsulePage');
    await this.floatWin.showWindow();
  }

  async expandToPanel(context: HomeContext): Promise<void> {
    if (!this.floatWin) return;
    
    this.currentLevel = 'panel';
    await this.floatWin.resize({ width: 460, height: 780 });
    await this.floatWin.moveWindowTo({ x: 540, y: 60 });
    await this.floatWin.setUIContent('pages/HomePanelPage');
    
    emitter.emit('showHomePanel', { data: context });
  }

  async autoExpandOnAlert(context: HomeContext): Promise<void> {
    if (!this.floatWin || this.currentLevel !== 'capsule') return;
    
    if (context.securityStatus === 'emergency' || context.securityStatus === 'alert') {
      await this.expandToPanel(context);
    }
  }

  async collapseToCapsule(): Promise<void> {
    if (!this.floatWin) return;
    
    this.currentLevel = 'capsule';
    await this.floatWin.resize({ width: 100, height: 100 });
    await this.floatWin.moveWindowTo({ x: 950, y: 150 });
    await this.floatWin.setUIContent('pages/HomeCapsulePage');
  }

  destroy(): void {
    this.floatWin?.destroyWindow();
  }
}

4.5 家居胶囊页面(HomeCapsulePage)

// pages/HomeCapsulePage.ets
import { emitter } from '@kit.BasicServicesKit';
import { SecurityLevel } from '../engine/HomeContextEngine';

@Entry
@Component
struct HomeCapsulePage {
  @State securityStatus: SecurityLevel = SecurityLevel.SAFE;
  @State activeDeviceCount: number = 0;
  @State temperature: number = 24;
  @State isListening: boolean = false;

  private securityIcons: Record<<SecurityLevel, string> = {
    [SecurityLevel.SAFE]: '🔒',
    [SecurityLevel.CAUTION]: '⚠️',
    [SecurityLevel.ALERT]: '🚨',
    [SecurityLevel.EMERGENCY]: '‼️'
  };

  aboutToAppear() {
    emitter.on('updateHomeContext', (event) => {
      const ctx = event.data;
      this.securityStatus = ctx?.securityStatus || SecurityLevel.SAFE;
      this.activeDeviceCount = ctx?.activeDevices?.length || 0;
      this.temperature = ctx?.environment?.temperature || 24;
    });
  }

  build() {
    Stack() {
      // 安防告警脉冲
      if (this.securityStatus === SecurityLevel.ALERT || this.securityStatus === SecurityLevel.EMERGENCY) {
        Circle()
          .width(110)
          .height(110)
          .fill(this.securityStatus === SecurityLevel.EMERGENCY ? '#FF1744' : '#FF9100')
          .opacity(0.2)
          .animation({
            duration: this.securityStatus === SecurityLevel.EMERGENCY ? 500 : 1000,
            iterations: -1,
            curve: Curve.EaseInOut,
            playMode: PlayMode.Alternate
          })
      }

      Column() {
        // 安防图标
        Text(this.securityIcons[this.securityStatus])
          .fontSize(28)

        // 温度
        Text(`${this.temperature}`)
          .fontSize(14)
          .fontColor('#666')
          .margin({ top: 2 })

        // 活跃设备数
        Text(`${this.activeDeviceCount}设备`)
          .fontSize(10)
          .fontColor('#999')
      }
      .width(100)
      .height(100)
      .justifyContent(FlexAlign.Center)
      .backgroundColor('rgba(255, 255, 255, 0.95)')
      .borderRadius(50)
      .shadow({ radius: 15, color: 'rgba(0,0,0,0.12)' })
      .gesture(
        GestureGroup(GestureMode.Sequence,
          TapGesture({ count: 1 })
            .onAction(() => emitter.emit('expandToPanel')),
          LongPressGesture({ duration: 800 })
            .onAction(() => this.toggleVoiceMode())
        )
      )
    }
    .width('100%')
    .height('100%')
    .align(Alignment.Center)
  }

  private toggleVoiceMode() {
    this.isListening = !this.isListening;
    emitter.emit('toggleVoiceMode', { data: { active: this.isListening } });
  }
}

4.6 家居面板页面(HomePanelPage)

// pages/HomePanelPage.ets
import { emitter } from '@kit.BasicServicesKit';
import { HomeContext, SmartDevice, DeviceType, SecurityLevel } from '../engine/HomeContextEngine';
import { HomeResponse } from '../agent/HomeAgentEngine';

@Entry
@Component
struct HomePanelPage {
  @State context: HomeContext | null = null;
  @State selectedRoom: string = 'all';
  @State isVoiceMode: boolean = false;
  @State voiceText: string = '';

  private roomFilters: string[] = ['all', 'living_room', 'bedroom', 'kitchen'];

  aboutToAppear() {
    emitter.on('showHomePanel', (event) => {
      this.context = event.data;
    });
  }

  build() {
    Column() {
      // 顶部标题栏
      Row() {
        Text('🏠 智能家居')
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .layoutWeight(1)
        
        Button(this.isVoiceMode ? '🎤' : '⌨️')
          .fontSize(14)
          .backgroundColor('#f0f0f0')
          .onClick(() => this.isVoiceMode = !this.isVoiceMode)
        
        Button('收起')
          .fontSize(12)
          .backgroundColor('#f0f0f0')
          .fontColor('#333')
          .margin({ left: 8 })
          .onClick(() => emitter.emit('collapseToCapsule'))
      }
      .width('100%')
      .padding(16)

      // 环境状态卡片
      Row() {
        Column() {
          Text('🌡️')
            .fontSize(24)
          Text(`${this.context?.environment?.temperature || 24}`)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
          Text('温度')
            .fontSize(10)
            .fontColor('#999')
        }
        .layoutWeight(1)

        Column() {
          Text('💧')
            .fontSize(24)
          Text(`${this.context?.environment?.humidity || 50}%`)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
          Text('湿度')
            .fontSize(10)
            .fontColor('#999')
        }
        .layoutWeight(1)

        Column() {
          Text('💡')
            .fontSize(24)
          Text(`${this.context?.environment?.illuminance || 300}lx`)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
          Text('光照')
            .fontSize(10)
            .fontColor('#999')
        }
        .layoutWeight(1)

        Column() {
          Text('🌬️')
            .fontSize(24)
          Text(`${this.context?.environment?.airQuality || 85}`)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
          Text('空气')
            .fontSize(10)
            .fontColor('#999')
        }
        .layoutWeight(1)
      }
      .width('100%')
      .padding(12)
      .backgroundColor('#f8f9fa')
      .borderRadius(12)
      .margin({ bottom: 12 })

      // 安防状态
      if (this.context?.securityStatus !== SecurityLevel.SAFE) {
        Row() {
          Text(this.context?.securityStatus === SecurityLevel.EMERGENCY ? '‼️' : '🚨')
            .fontSize(20)
          Text(`安防${this.context?.securityStatus === SecurityLevel.EMERGENCY ? '紧急' : '警戒'}状态`)
            .fontSize(14)
            .fontColor('#FFF')
            .fontWeight(FontWeight.Bold)
            .layoutWeight(1)
            .margin({ left: 8 })
          Button('查看详情')
            .fontSize(12)
            .backgroundColor('#FFF')
            .fontColor('#FF1744')
            .onClick(() => this.viewSecurityDetails())
        }
        .width('100%')
        .padding(12)
        .backgroundColor(
          this.context?.securityStatus === SecurityLevel.EMERGENCY ? '#FF1744' : '#FF9100'
        )
        .borderRadius(8)
        .margin({ bottom: 12 })
      }

      // 房间筛选
      Row() {
        ForEach(this.roomFilters, (room: string) => {
          Button(this.getRoomName(room))
            .fontSize(12)
            .backgroundColor(this.selectedRoom === room ? '#2979FF' : '#f0f0f0')
            .fontColor(this.selectedRoom === room ? '#FFF' : '#666')
            .margin({ right: 8 })
            .onClick(() => this.selectedRoom = room)
        })
      }
      .width('100%')
      .margin({ bottom: 12 })

      // 设备列表
      List() {
        ForEach(this.filteredDevices(), (device: SmartDevice) => {
          ListItem() {
            this.DeviceCard(device)
          }
        })
      }
      .width('100%')
      .layoutWeight(1)

      // 快速场景
      Row() {
        Button('🏠 回家')
          .fontSize(12)
          .backgroundColor('#E8F5E9')
          .fontColor('#2E7D32')
          .layoutWeight(1)
          .onClick(() => this.activateScene('home'))

        Button('😴 睡眠')
          .fontSize(12)
          .backgroundColor('#E3F2FD')
          .fontColor('#1565C0')
          .margin({ left: 8 })
          .layoutWeight(1)
          .onClick(() => this.activateScene('sleep'))

        Button('🎬 观影')
          .fontSize(12)
          .backgroundColor('#F3E5F5')
          .fontColor('#7B1FA2')
          .margin({ left: 8 })
          .layoutWeight(1)
          .onClick(() => this.activateScene('movie'))

        Button('🚪 离家')
          .fontSize(12)
          .backgroundColor('#FFEBEE')
          .fontColor('#C62828')
          .margin({ left: 8 })
          .layoutWeight(1)
          .onClick(() => this.activateScene('away'))
      }
      .width('100%')
      .padding({ top: 12 })

      // 语音输入
      if (this.isVoiceMode) {
        Row() {
          TextInput({ placeholder: '语音输入或打字指令...', text: this.voiceText })
            .fontSize(14)
            .layoutWeight(1)
            .onSubmit((value) => this.submitCommand(value))
          
          Button('🎤')
            .fontSize(14)
            .backgroundColor('#2979FF')
            .onClick(() => this.startVoiceInput())
        }
        .width('100%')
        .padding(12)
        .backgroundColor('#f8f9fa')
        .borderRadius(8)
        .margin({ top: 8 })
      }
    }
    .width('100%')
    .height('100%')
    .padding(16)
    .backgroundColor('#FFF')
    .borderRadius(16)
  }

  @Builder
  DeviceCard(device: SmartDevice) {
    Row() {
      Text(this.getDeviceIcon(device.type))
        .fontSize(24)
        .margin({ right: 12 })

      Column() {
        Text(device.name)
          .fontSize(14)
          .fontWeight(FontWeight.Medium)
          .width('100%')
        
        Text(this.getDeviceStatusText(device))
          .fontSize(12)
          .fontColor('#666')
          .width('100%')
      }
      .layoutWeight(1)

      Toggle({ type: ToggleType.Switch, isOn: device.status.power === 'on' })
        .selectedColor('#2979FF')
        .onChange((isOn) => {
          emitter.emit('controlDevice', { 
            data: { 
              deviceId: device.id, 
              action: isOn ? 'turn_on' : 'turn_off' 
            } 
          });
        })

      if (device.status.brightness !== undefined) {
        Slider({
          value: device.status.brightness,
          min: 0,
          max: 100
        })
          .width(80)
          .onChange((value) => {
            emitter.emit('controlDevice', {
              data: { deviceId: device.id, action: 'set_brightness', value }
            });
          })
      }
    }
    .width('100%')
    .padding(12)
    .backgroundColor('#fff')
    .borderRadius(8)
    .margin({ bottom: 8 })
    .shadow({ radius: 4, color: 'rgba(0,0,0,0.05)' })
  }

  private filteredDevices(): SmartDevice[] {
    if (!this.context?.activeDevices) return [];
    if (this.selectedRoom === 'all') return this.context.activeDevices;
    return this.context.activeDevices.filter(d => d.location === this.selectedRoom);
  }

  private getRoomName(room: string): string {
    const names: Record<string, string> = {
      'all': '全部',
      'living_room': '客厅',
      'bedroom': '卧室',
      'kitchen': '厨房'
    };
    return names[room] || room;
  }

  private getDeviceIcon(type: DeviceType): string {
    const icons: Record<string, string> = {
      'light': '💡',
      'air_conditioner': '❄️',
      'curtain': '🪟',
      'camera': '📷',
      'smart_lock': '🔐',
      'sensor': '📡',
      'switch': '🔘',
      'speaker': '🔊'
    };
    return icons[type] || '📟';
  }

  private getDeviceStatusText(device: SmartDevice): string {
    if (device.status.power === 'off') return '已关闭';
    if (device.status.temperature !== undefined) return `${device.status.temperature}`;
    if (device.status.brightness !== undefined) return `亮度 ${device.status.brightness}%`;
    return '运行中';
  }

  private viewSecurityDetails() {
    emitter.emit('viewSecurityDetails');
  }

  private activateScene(scene: string) {
    emitter.emit('activateScene', { data: { scene } });
  }

  private submitCommand(command: string) {
    emitter.emit('processCommand', { data: { command } });
    this.voiceText = '';
  }

  private startVoiceInput() {
    emitter.emit('startVoiceInput');
  }
}

4.7 主入口与系统集成(Index.ets)

// Index.ets
import { HomeContextEngine, SecurityLevel } from './engine/HomeContextEngine';
import { HomeLightingController } from './lighting/HomeLightingController';
import { HomeFloatWindow } from './float/HomeFloatWindow';
import { HomeAgentEngine } from './agent/HomeAgentEngine';
import { emitter } from '@kit.BasicServicesKit';

@Entry
@Component
struct SmartHomeApp {
  private homeEngine: HomeContextEngine = new HomeContextEngine();
  private lightController: HomeLightingController = new HomeLightingController();
  private floatWindow: HomeFloatWindow = new HomeFloatWindow();
  private agentEngine: HomeAgentEngine = new HomeAgentEngine();

  aboutToAppear() {
    this.initSystem();
  }

  aboutToDisappear() {
    this.homeEngine.destroy();
    this.lightController.reset();
    this.floatWindow.destroy();
    this.agentEngine.destroy();
  }

  async initSystem() {
    // 1. 初始化沉浸光感
    await this.lightController.init();

    // 2. 初始化悬浮窗
    await this.floatWindow.create();

    // 3. 初始化智能体引擎
    await this.agentEngine.init();

    // 4. 初始化家居引擎
    await this.homeEngine.init();

    // 当家居上下文变化时,更新光效和悬浮窗
    this.homeEngine.onContextChange(async (context) => {
      // 更新光效
      await this.lightController.updateByContext({
        security: context.securityStatus,
        energy: context.energyStatus,
        environment: context.environment,
        time: context.timeContext,
        location: context.location
      });
      
      // 严重告警自动展开
      await this.floatWindow.autoExpandOnAlert(context);
      
      // 更新悬浮窗
      emitter.emit('updateHomeContext', { data: context });

      // 生成主动建议
      const suggestions = await this.agentEngine.generateProactiveSuggestions(context);
      if (suggestions.length > 0) {
        // 推送建议到悬浮窗
        emitter.emit('proactiveSuggestions', { data: suggestions });
      }
    });

    // 5. 设置事件监听
    this.setupEventListeners();
  }

  private setupEventListeners() {
    emitter.on('expandToPanel', async () => {
      const context = this.homeEngine.getCurrentContext();
      if (context) {
        await this.floatWindow.expandToPanel(context);
      }
    });

    emitter.on('collapseToCapsule', async () => {
      await this.floatWindow.collapseToCapsule();
    });

    emitter.on('controlDevice', async (event) => {
      const { deviceId, action, value } = event.data || {};
      const success = await this.homeEngine.controlDevice(deviceId, action, value);
      await this.lightController.controlFeedback(success);
    });

    emitter.on('activateScene', async (event) => {
      const scene = event.data?.scene;
      const context = this.homeEngine.getCurrentContext();
      if (scene && context) {
        const response = await this.agentEngine.processCommand(`切换到${scene}模式`, context);
        if (response.actions) {
          for (const action of response.actions) {
            await this.homeEngine.controlDevice(action.deviceId, action.action, action.value);
          }
        }
        await this.lightController.sceneTransition(scene);
      }
    });

    emitter.on('processCommand', async (event) => {
      const command = event.data?.command;
      const context = this.homeEngine.getCurrentContext();
      if (command && context) {
        const response = await this.agentEngine.processCommand(command, context);
        // 执行控制动作
        if (response.actions) {
          for (const action of response.actions) {
            await this.homeEngine.controlDevice(action.deviceId, action.action, action.value);
          }
        }
        // 显示回复
        // ...
      }
    });

    emitter.on('toggleVoiceMode', (event) => {
      // 切换语音模式
    });
  }

  build() {
    Column() {
      Text('🏠 HarmonyOS智能家居中枢')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ bottom: 8 })
      
      Text('AI智能体正在守护您的家...')
        .fontSize(14)
        .fontColor('#666')
      
      Text('悬浮窗常驻显示,语音/手势随时控制')
        .fontSize(12)
        .fontColor('#999')
        .margin({ top: 4 })
        .textAlign(TextAlign.Center)

      // 家居概览
      Column() {
        Text('📊 家居概览')
          .fontSize(16)
          .fontWeight(FontWeight.Medium)
          .margin({ bottom: 12 })

        Row() {
          Column() {
            Text('12')
              .fontSize(28)
              .fontWeight(FontWeight.Bold)
              .fontColor('#2979FF')
            Text('在线设备')
              .fontSize(12)
              .fontColor('#999')
          }
          .layoutWeight(1)

          Column() {
            Text('🔒')
              .fontSize(28)
            Text('安全')
              .fontSize(12)
              .fontColor('#999')
          }
          .layoutWeight(1)

          Column() {
            Text('24℃')
              .fontSize(28)
              .fontWeight(FontWeight.Bold)
              .fontColor('#00C853')
            Text('舒适')
              .fontSize(12)
              .fontColor('#999')
          }
          .layoutWeight(1)
        }
        .width('100%')
      }
      .width('90%')
      .padding(20)
      .backgroundColor('#f8f9fa')
      .borderRadius(12)
      .margin({ top: 32 })

      // 当前状态
      Row() {
        Text('系统状态:')
          .fontSize(14)
          .fontColor('#666')
        
        Text('🟢 正常运行')
          .fontSize(14)
          .fontColor('#00C853')
          .fontWeight(FontWeight.Medium)
      }
      .margin({ top: 20 })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

五、配置文件

// module.json5
{
  "module": {
    "name": "SmartHomeHub",
    "type": "entry",
    "description": "鸿蒙智能体智能家居控制中枢",
    "mainElement": "EntryAbility",
    "deviceTypes": ["phone", "tablet", "2in1"],
    "pages": "$profile:main_pages",
    "abilities": [
      {
        "name": "EntryAbility",
        "srcEntry": "./ets/entryability/EntryAbility.ets",
        "description": "智能家居中枢主入口",
        "icon": "$media:layered_image",
        "label": "AI智能家居",
        "startWindowIcon": "$media:startIcon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": ["entity.system.home"],
            "actions": ["action.system.home"]
          }
        ]
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.SYSTEM_FLOAT_WINDOW",
        "reason": "需要悬浮窗权限以常驻显示家居状态"
      },
      {
        "name": "ohos.permission.DISTRIBUTED_DEVICE_STATE_CHANGE",
        "reason": "需要分布式设备状态变更权限"
      },
      {
        "name": "ohos.permission.ACCESS_SENSORS",
        "reason": "读取环境传感器数据"
      },
      {
        "name": "ohos.permission.INTERNET",
        "reason": "连接云端智能体服务"
      },
      {
        "name": "ohos.permission.ACCESS_AI_MODEL",
        "reason": "使用端侧AI模型进行语义理解"
      },
      {
        "name": "ohos.permission.MICROPHONE",
        "reason": "支持语音控制交互"
      }
    ]
  }
}

六、效果展示与使用场景

6.1 典型家居场景

场景A:烹饪助手

用户在厨房做饭,双手沾满面粉。语音说"把厨房灯调亮一点",悬浮窗AI智能体识别指令,自动将厨房灯光从50%调至80%,边框泛起温暖的橙色光效表示"烹饪模式"。同时建议"检测到油烟较大,建议开启抽油烟机"。

场景B:深夜安防

凌晨2点,门口传感器检测到异常震动。设备四周边框立即泛起红色快速脉冲光效,悬浮窗自动展开显示门口摄像头画面。AI智能体分析:“检测到疑似人影,但动作特征与宠物相似,建议查看确认而非直接报警”,避免误报惊扰。

场景C:节能建议

连续三天18:00-20:00空调设定22℃,AI智能体在悬浮窗推送:“检测到您该时段空调温度偏低,调整为26℃可节省15%电费且体感差异不大”,边框泛起绿色光效表示"节能建议"。用户一键采纳,自动调整温度设定。

6.2 光效语义设计

家居状态 光效表现 用户提示
安全正常 底部翠绿微光 家中安全,放心
设备运行 对应位置柔和色 设备正常运行
能耗良好 底部绿色呼吸 节能模式运行中
温度不适 全边框红/蓝呼吸 建议调节温控
安防警戒 全边框黄色波浪 注意查看详情
安防紧急 全边框红色快闪 立即处理
场景切换 全边框渐变过渡 场景切换中

七、性能与隐私优化

7.1 设备连接策略

// 设备连接优化
const deviceStrategy = {
  // 连接优先级
  priority: ['local_network', 'cloud_relay', 'bluetooth'],
  
  // 心跳间隔
  heartbeat: {
    normal: 30000,    // 正常:30秒
    active: 10000,    // 活跃:10秒
    alert: 5000       // 告警:5秒
  },
  
  // 离线缓存
  offlineCache: {
    enabled: true,
    maxCommands: 20,  // 最多缓存20条指令
    syncOnReconnect: true
  }
};

7.2 隐私保护

  • 本地优先:所有设备控制优先在本地网络完成
  • 数据最小化:仅上传必要的设备状态,不上传用户行为
  • 权限隔离:不同家庭成员看到不同的设备权限
  • 语音本地识别:常用指令本地识别,敏感操作云端确认

八、总结与展望

本文展示了如何基于HarmonyOS 6(API 23)的悬浮导航沉浸光感能力,构建一个鸿蒙智能体驱动的沉浸式智能家居控制中枢。与传统智能家居APP不同,它具备三个核心创新:

  1. 常驻感知:悬浮窗常驻屏幕边缘,家居状态随时可见,语音/手势随时控制
  2. 光效氛围:通过设备边框光效实现"无屏感知"的家居状态监控
  3. 情境智能:AI智能体主动学习用户习惯,主动推荐场景化控制方案

未来演进方向:

  • 多设备协同:手机悬浮窗 + 平板控制面板 + 音箱语音交互
  • 数字孪生:家中3D模型可视化,悬浮窗即数字孪生入口
  • 预测性维护:AI预测设备故障,提前安排维修
  • 能源优化:结合电网峰谷电价,自动优化用电策略

HarmonyOS 6的智能体框架和系统级交互创新,正在让"AI管家常驻身边"成为现实。对于智能家居用户而言,这不仅是一个控制工具,更是一位24小时在线、懂习惯、懂场景、懂节能的智能生活伙伴。


转载自:https://blog.csdn.net/u014727709/article/details/161367547
欢迎 👍点赞✍评论⭐收藏,欢迎指正

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐