在这里插入图片描述

每日一句正能量

“守住本心,格局自会慢慢拓宽,内心才会多一份从容与安宁。”
外界的声音会扰乱方向。当你明确自己的核心原则(本心),不因他人评价而动摇,你的心理容量(格局)就会变大——能容纳更多不同、更多不确定性。格局一大,琐事就小了,从容与安宁自然到来。

摘要

摘要:2026年,中国教育数字化战略行动进入深水区,全国中小学智慧教育平台注册用户突破1.2亿,但传统教育管理系统面临教学资源分散、学情分析滞后、家校协同低效三大痛点。HarmonyOS 6(API 23)引入的鸿蒙智能体框架(HMAF)将AI能力下沉至系统层,配合悬浮导航与沉浸光感特性,为PC端智慧教育管理带来了"学情即光效、协作即导航"的全新交互范式。本文将实战开发一款面向HarmonyOS PC的"智教云枢"应用,展示如何利用HMAF构建"学情采集-智能诊断-资源推荐-家校协同"四层智能体协作架构,通过悬浮导航实现教学场景实时切换,基于沉浸光感打造"专注度即氛围"的沉浸体验,以及基于多窗口架构构建浮动学情面板、实时课堂视窗和作业批改助手的协作教学体验。

一、前言:智慧教育管理的范式革新

2026年,中国教育数字化战略行动已进入"智能化升级"新阶段。教育部数据显示,全国中小学智慧教育平台注册用户突破1.2亿,但传统教育管理系统仍面临三大核心痛点:

  1. 学情洞察滞后:教师依赖月考、周测等传统手段了解学生学习状态,无法实时掌握课堂专注度、作业完成质量、知识点掌握程度等多维数据
  2. 资源匹配粗放:教学资源库虽然庞大,但缺乏基于学生个体差异的精准推荐,"千人一面"的资源推送导致学习效率低下
  3. 家校协同断裂:家长端、教师端、学生端数据孤岛严重,家长无法实时了解孩子在校表现,教师难以获取家庭学习环境数据

HarmonyOS 6(API 23)引入的**鸿蒙智能体框架(HarmonyOS Multi-agent Framework,HMAF)将AI能力从应用层下沉至系统层,配合悬浮导航(Float Navigation)沉浸光感(Immersive Light Effects)**特性,为PC端智慧教育管理带来了"学情即光效、协作即导航"的全新交互范式。

本文核心亮点

  • 学情状态光效:根据班级整体学习状态(专注/分散/疲劳/活跃)动态切换环境光色与脉冲节奏
  • 悬浮教学导航:底部悬浮页签替代传统侧边菜单,支持教学场景(课堂/作业/考试/家校)快速切换与透明度调节
  • HMAF四层智能体协作:基于Agent Framework Kit构建"学情采集-智能诊断-资源推荐-家校协同"四层智能体协作架构
  • 多窗口教学协作:主教学窗口 + 浮动学情面板 + 实时课堂视窗 + 作业批改助手窗口的光效联动
  • 意图感知沉浸体验:通过Intents Kit实时理解教师教学意图,自动调整界面光效与导航形态

在这里插入图片描述

二、核心特性解析

2.1 悬浮导航(Float Navigation)

悬浮导航是HarmonyOS 6引入的全新底部导航交互模式,主要特点包括:

  • 悬浮层级设计:导航栏悬浮于内容之上,不占用布局空间
  • 智能避让机制:内容区域自动适配导航栏高度,避免遮挡
  • 动态透明度:支持根据滑动状态动态调整导航栏透明度(强85%/平衡70%/弱55%三档)
  • 手势融合:与系统全面屏手势无缝衔接

2.2 沉浸光感(Immersive Light Effects)

沉浸光感是HarmonyOS 6的视觉增强系统,核心能力包括:

  • P3广色域支持:色彩表现更丰富鲜艳
  • 安全区布局优化:组件背景默认延伸至非安全区(AI导航栏、状态栏)
  • 玻璃拟态效果:支持半透明、磨砂玻璃等现代视觉效果
  • 系统级光效同步:锁屏、主屏、控制面板、通知面板光效统一

2.3 HMAF(HarmonyOS Multi-agent Framework)

HMAF是HarmonyOS 6推出的系统级智能体生态框架,首批上线80+智能体。 其核心架构分为三层:

层级 职责 开发者关注点
HMAF 系统级智能体生态框架 小艺入口、多Agent协同、系统调度策略
Agent Framework Kit 应用侧SDK(API 20+) FunctionComponentFunctionController、应用内嵌Agent UI
A2A协议 Agent-to-Agent互操作标准 Agent Card发布、跨应用任务委托

在这里插入图片描述

三、实战案例:打造"智教云枢"智慧教育平台

3.1 项目配置

module.json5中声明所需权限和依赖:

{
  "module": {
    "name": "SmartEducationEntry",
    "type": "entry",
    "description": "智教云枢 - 智慧教育AI智能体管理平台",
    "mainElement": "EducationAbility",
    "abilities": [
      {
        "name": "EducationAbility",
        "srcEntry": "./ets/abilities/EducationAbility.ets",
        "description": "主教学窗口Ability",
        "icon": "$media:icon",
        "label": "$string:EntryAbility_label",
        "startWindowIcon": "$media:startIcon",
        "startWindowBackground": "$color:start_window_background",
        "exported": true,
        "skills": [
          {
            "entities": ["entity.system.home"],
            "actions": ["action.system.home"]
          }
        ]
      },
      {
        "name": "StudentPanelAbility",
        "srcEntry": "./ets/abilities/StudentPanelAbility.ets",
        "description": "浮动学情面板",
        "launchType": "multiton"
      },
      {
        "name": "ClassroomViewAbility",
        "srcEntry": "./ets/abilities/ClassroomViewAbility.ets",
        "description": "实时课堂视窗",
        "launchType": "multiton"
      }
    ],
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.GET_NETWORK_INFO"
      },
      {
        "name": "ohos.permission.DISTRIBUTED_DATASYNC"
      }
    ],
    "dependencies": [
      {
        "moduleName": "agent_framework_kit",
        "bundleName": "com.huawei.hmos.agentframework"
      }
    ]
  }
}

3.2 窗口沉浸配置(EducationAbility.ets)

代码亮点:本段代码实现了HarmonyOS 6 PC端窗口的全屏沉浸配置,通过WindowStage获取主窗口后,启用沉浸模式并设置安全区背景延伸,同时根据教学场景动态调整系统光效颜色,实现"学情即氛围"的视觉体验。

// entry/src/main/ets/abilities/EducationAbility.ets
import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';

// 教学场景枚举
export enum TeachingScene {
  CLASSROOM = 'classroom',    // 课堂教学
  HOMEWORK = 'homework',      // 作业管理
  EXAM = 'exam',              // 考试分析
  HOME_SCHOOL = 'homeSchool'  // 家校协同
}

// 学情状态枚举(对应不同光效)
export enum LearningState {
  FOCUSED = 'focused',        // 专注 - 宁静蓝
  SCATTERED = 'scattered',    // 分散 - 警示橙
  FATIGUED = 'fatigued',      // 疲劳 - 柔和紫
  ACTIVE = 'active'           // 活跃 - 生机绿
}

export default class EducationAbility extends UIAbility {
  private mainWindow: window.Window | null = null;
  private currentScene: TeachingScene = TeachingScene.CLASSROOM;
  private currentLearningState: LearningState = LearningState.FOCUSED;

  onWindowStageCreate(windowStage: window.WindowStage): void {
    hilog.info(0x0000, 'SmartEducation', 'EducationAbility onWindowStageCreate');
    
    // 加载主页面
    windowStage.loadContent('pages/EducationDashboard', (err) => {
      if (err.code) {
        hilog.error(0x0000, 'SmartEducation', 'Failed to load content: %{public}s', JSON.stringify(err));
        return;
      }
      hilog.info(0x0000, 'SmartEducation', 'Content loaded successfully');
    });

    // 配置窗口沉浸模式(HarmonyOS 6 PC端特性)
    this.configureImmersiveWindow(windowStage);
  }

  private async configureImmersiveWindow(windowStage: window.WindowStage): Promise<void> {
    try {
      this.mainWindow = await windowStage.getMainWindow();
      
      // 启用窗口全屏沉浸模式
      await this.mainWindow.setWindowLayoutFullScreen(true);
      
      // 设置安全区背景延伸(沉浸光感核心配置)
      await this.mainWindow.setWindowBackgroundColor('#F5F7FA');
      
      // 获取安全区信息
      const avoidArea = this.mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
      const navBarHeight = avoidArea.bottomRect.height;
      const statusBarHeight = avoidArea.topRect.height;
      
      // 存储安全区高度供全局使用
      AppStorage.setOrCreate('navBarHeight', navBarHeight);
      AppStorage.setOrCreate('statusBarHeight', statusBarHeight);
      
      hilog.info(0x0000, 'SmartEducation', 
        'Window configured: statusBar=%{public}d, navBar=%{public}d', 
        statusBarHeight, navBarHeight);
      
    } catch (error) {
      hilog.error(0x0000, 'SmartEducation', 
        'Failed to configure window: %{public}s', JSON.stringify(error));
    }
  }

  // 根据教学场景和学情状态更新系统光效
  public async updateImmersiveLighting(scene: TeachingScene, state: LearningState): Promise<void> {
    if (!this.mainWindow) return;
    
    this.currentScene = scene;
    this.currentLearningState = state;
    
    // 场景-光效映射表
    const sceneLightEffects: Record<TeachingScene, Record<LearningState, string>> = {
      [TeachingScene.CLASSROOM]: {
        [LearningState.FOCUSED]: '#E3F2FD',    // 宁静蓝
        [LearningState.SCATTERED]: '#FFF3E0',  // 警示橙
        [LearningState.FATIGUED]: '#F3E5F5',   // 柔和紫
        [LearningState.ACTIVE]: '#E8F5E9'      // 生机绿
      },
      [TeachingScene.HOMEWORK]: {
        [LearningState.FOCUSED]: '#E1F5FE',
        [LearningState.SCATTERED]: '#FFE0B2',
        [LearningState.FATIGUED]: '#EDE7F6',
        [LearningState.ACTIVE]: '#C8E6C9'
      },
      [TeachingScene.EXAM]: {
        [LearningState.FOCUSED]: '#BBDEFB',
        [LearningState.SCATTERED]: '#FFCC80',
        [LearningState.FATIGUED]: '#D1C4E9',
        [LearningState.ACTIVE]: '#A5D6A7'
      },
      [TeachingScene.HOME_SCHOOL]: {
        [LearningState.FOCUSED]: '#90CAF9',
        [LearningState.SCATTERED]: '#FFB74D',
        [LearningState.FATIGUED]: '#B39DDB',
        [LearningState.ACTIVE]: '#81C784'
      }
    };
    
    const lightColor = sceneLightEffects[scene][state];
    
    try {
      // 设置窗口背景光效(HarmonyOS 6沉浸光感API)
      await this.mainWindow.setWindowBackgroundColor(lightColor);
      
      // 触发系统级光效同步(通知面板、控制面板联动)
      await this.mainWindow.setSystemBarProperties({
        statusBarColor: lightColor,
        navigationBarColor: lightColor
      });
      
      hilog.info(0x0000, 'SmartEducation', 
        'Light effect updated: scene=%{public}s, state=%{public}s, color=%{public}s',
        scene, state, lightColor);
        
    } catch (error) {
      hilog.error(0x0000, 'SmartEducation', 
        'Failed to update light effect: %{public}s', JSON.stringify(error));
    }
  }

  onDestroy(): void {
    hilog.info(0x0000, 'SmartEducation', 'EducationAbility onDestroy');
    this.mainWindow = null;
  }
}

3.3 悬浮教学导航组件(FloatTeachingNav.ets)

代码亮点:本组件实现了HarmonyOS 6特色的底部悬浮导航栏,支持教学场景的快速切换。核心特性包括:玻璃拟态背景(backgroundBlurStyle+backdropFilter)、三档透明度调节(强85%/平衡70%/弱55%)、长按展开透明度滑块、智能体状态实时徽章(红色圆点提示待处理事项),以及与系统安全区的智能避让。

// entry/src/main/ets/components/FloatTeachingNav.ets
import { window } from '@kit.ArkUI';
import { vibrator } from '@kit.SensorServiceKit';
import { TeachingScene, LearningState } from '../abilities/EducationAbility';

// 透明度档位枚举
export enum TransparencyLevel {
  STRONG = 0.85,    // 强效果:高透明度,玻璃感明显
  BALANCED = 0.70,  // 平衡效果:适中透明度
  WEAK = 0.55       // 弱效果:低透明度,更清晰
}

// 导航项配置
interface NavItem {
  icon: Resource;
  label: string;
  scene: TeachingScene;
  badge?: number;    // 待处理事项数量
  agentStatus?: 'idle' | 'running' | 'alert';  // 智能体状态
}

@Component
export struct FloatTeachingNav {
  @State currentScene: TeachingScene = TeachingScene.CLASSROOM;
  @State navTransparency: number = TransparencyLevel.BALANCED;
  @State isExpanded: boolean = false;
  @State bottomAvoidHeight: number = 0;
  @State learningState: LearningState = LearningState.FOCUSED;
  
  // 智能体待处理任务数
  @State agentTasks: Record<TeachingScene, number> = {
    [TeachingScene.CLASSROOM]: 3,
    [TeachingScene.HOMEWORK]: 12,
    [TeachingScene.EXAM]: 5,
    [TeachingScene.HOME_SCHOOL]: 8
  };

  // 导航项配置
  private navItems: NavItem[] = [
    { 
      icon: $r('app.media.ic_classroom'), 
      label: '课堂教学', 
      scene: TeachingScene.CLASSROOM,
      badge: 3,
      agentStatus: 'running'
    },
    { 
      icon: $r('app.media.ic_homework'), 
      label: '作业管理', 
      scene: TeachingScene.HOMEWORK,
      badge: 12,
      agentStatus: 'alert'
    },
    { 
      icon: $r('app.media.ic_exam'), 
      label: '考试分析', 
      scene: TeachingScene.EXAM,
      badge: 5,
      agentStatus: 'idle'
    },
    { 
      icon: $r('app.media.ic_home_school'), 
      label: '家校协同', 
      scene: TeachingScene.HOME_SCHOOL,
      badge: 8,
      agentStatus: 'running'
    }
  ];

  // 场景切换回调
  onSceneChange?: (scene: TeachingScene) => void;

  aboutToAppear(): void {
    this.getBottomAvoidArea();
    this.startLearningStateMonitor();
  }

  private async getBottomAvoidArea(): Promise<void> {
    try {
      const mainWindow = await window.getLastWindow();
      const avoidArea = mainWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
      this.bottomAvoidHeight = avoidArea.bottomRect.height;
    } catch (error) {
      console.error('Failed to get avoid area:', error);
    }
  }

  // 模拟学情状态监控(实际应接入HMAF学情采集智能体)
  private startLearningStateMonitor(): void {
    setInterval(() => {
      const states = [LearningState.FOCUSED, LearningState.SCATTERED, LearningState.FATIGUED, LearningState.ACTIVE];
      this.learningState = states[Math.floor(Math.random() * states.length)];
    }, 30000); // 每30秒模拟一次状态变化
  }

  build() {
    Stack({ alignContent: Alignment.Bottom }) {
      // 内容区域(由父组件传入)
      Column() {
        this.contentBuilder()
      }
      .padding({ 
        top: 16, 
        bottom: this.bottomAvoidHeight + (this.isExpanded ? 140 : 100) 
      })

      // 悬浮导航栏容器
      Column() {
        // 玻璃拟态背景层
        Stack() {
          // 背景模糊效果(HarmonyOS 6新特性)
          Column()
            .width('100%')
            .height('100%')
            .backgroundBlurStyle(BlurStyle.REGULAR)
            .opacity(this.navTransparency)
            .backdropFilter($r('sys.blur.20'))

          // 渐变光效层(根据学情状态动态变化)
          Column()
            .width('100%')
            .height('100%')
            .linearGradient({
              direction: GradientDirection.Top,
              colors: this.getStateGradientColors()
            })
        }
        .width('100%')
        .height('100%')
        .borderRadius(28)
        .shadow({
          radius: 24,
          color: 'rgba(0,0,0,0.12)',
          offsetX: 0,
          offsetY: -6
        })

        // 导航项
        Row() {
          ForEach(this.navItems, (item: NavItem) => {
            Column() {
              Stack() {
                Image(item.icon)
                  .width(28)
                  .height(28)
                  .fillColor(this.currentScene === item.scene ? this.getActiveColor() : '#666666')
                  .transition(TransitionEffect.OPACITY)

                // 选中指示器光效
                if (this.currentScene === item.scene) {
                  Column()
                    .width(48)
                    .height(48)
                    .backgroundColor(this.getActiveColor(0.2))
                    .borderRadius(24)
                    .blur(12)
                    .position({ x: -10, y: -10 })
                }

                // 智能体状态指示器
                if (item.agentStatus === 'running') {
                  Column()
                    .width(8)
                    .height(8)
                    .backgroundColor('#4CAF50')
                    .borderRadius(4)
                    .position({ x: 20, y: -4 })
                    .shadow({ radius: 4, color: 'rgba(76,175,80,0.6)' })
                } else if (item.agentStatus === 'alert') {
                  Column()
                    .width(8)
                    .height(8)
                    .backgroundColor('#FF5252')
                    .borderRadius(4)
                    .position({ x: 20, y: -4 })
                    .shadow({ radius: 4, color: 'rgba(255,82,82,0.6)' })
                }
              }
              .width(48)
              .height(48)

              Text(item.label)
                .fontSize(12)
                .fontColor(this.currentScene === item.scene ? this.getActiveColor() : '#999999')
                .margin({ top: 6 })
                .fontWeight(this.currentScene === item.scene ? FontWeight.Bold : FontWeight.Normal)

              // 待处理事项徽章
              if (item.badge && item.badge > 0) {
                Badge({
                  value: item.badge.toString(),
                  position: BadgePosition.RightTop,
                  style: { badgeSize: 18, badgeColor: '#FF5252' }
                }) {
                  Column().width(0).height(0)
                }
                .position({ x: 16, y: -36 })
              }
            }
            .layoutWeight(1)
            .onClick(() => {
              this.switchScene(item.scene);
            })
          })
        }
        .width('100%')
        .height(90)
        .padding({ left: 20, right: 20 })
        .justifyContent(FlexAlign.SpaceAround)

        // 透明度调节与学情状态指示(展开状态)
        if (this.isExpanded) {
          Column() {
            // 学情状态指示条
            Row() {
              Text('班级状态')
                .fontSize(11)
                .fontColor('#666666')
                .margin({ right: 8 })

              Row() {
                Circle()
                  .width(8)
                  .height(8)
                  .fill(this.getStateColor())
                Text(this.getStateLabel())
                  .fontSize(11)
                  .fontColor(this.getStateColor())
                  .margin({ left: 4 })
              }
              .layoutWeight(1)

              // 透明度滑块
              Slider({
                value: this.navTransparency * 100,
                min: 55,
                max: 85,
                step: 15,
                style: SliderStyle.InSet
              })
                .width(100)
                .onChange((value: number) => {
                  this.navTransparency = value / 100;
                })

              Text(`${Math.round(this.navTransparency * 100)}%`)
                .fontSize(11)
                .fontColor('#666666')
                .margin({ left: 8 })
            }
            .width('100%')
            .height(36)
            .padding({ left: 16, right: 16 })
          }
          .width('100%')
          .height(50)
          .backgroundColor('rgba(255,255,255,0.6)')
          .borderRadius({ topLeft: 16, topRight: 16 })
        }
      }
      .width('94%')
      .height(this.isExpanded ? 140 : 90)
      .margin({ 
        bottom: this.bottomAvoidHeight + 16, 
        left: '3%', 
        right: '3%' 
      })
      .animation({
        duration: 350,
        curve: Curve.Spring,
        iterations: 1
      })
      .gesture(
        LongPressGesture({ duration: 600 })
          .onAction(() => {
            this.isExpanded = !this.isExpanded;
            this.triggerHapticFeedback();
          })
      )
    }
    .width('100%')
    .height('100%')
  }

  // 根据学情状态获取渐变色
  private getStateGradientColors(): Array<[string, number]> {
    switch (this.learningState) {
      case LearningState.FOCUSED:
        return [['rgba(227,242,253,0.3)', 0.0], ['rgba(255,255,255,0.1)', 1.0]];
      case LearningState.SCATTERED:
        return [['rgba(255,243,224,0.3)', 0.0], ['rgba(255,255,255,0.1)', 1.0]];
      case LearningState.FATIGUED:
        return [['rgba(243,229,245,0.3)', 0.0], ['rgba(255,255,255,0.1)', 1.0]];
      case LearningState.ACTIVE:
        return [['rgba(232,245,233,0.3)', 0.0], ['rgba(255,255,255,0.1)', 1.0]];
    }
  }

  // 获取激活态颜色
  private getActiveColor(alpha?: number): string {
    const baseColors: Record<LearningState, string> = {
      [LearningState.FOCUSED]: '#2196F3',
      [LearningState.SCATTERED]: '#FF9800',
      [LearningState.FATIGUED]: '#9C27B0',
      [LearningState.ACTIVE]: '#4CAF50'
    };
    const color = baseColors[this.learningState];
    if (alpha !== undefined) {
      return color + Math.round(alpha * 255).toString(16).padStart(2, '0');
    }
    return color;
  }

  // 获取状态颜色
  private getStateColor(): string {
    return this.getActiveColor();
  }

  // 获取状态标签
  private getStateLabel(): string {
    const labels: Record<LearningState, string> = {
      [LearningState.FOCUSED]: '专注',
      [LearningState.SCATTERED]: '分散',
      [LearningState.FATIGUED]: '疲劳',
      [LearningState.ACTIVE]: '活跃'
    };
    return labels[this.learningState];
  }

  // 切换教学场景
  private switchScene(scene: TeachingScene): void {
    this.currentScene = scene;
    this.triggerHapticFeedback();
    
    // 通知父组件场景切换
    if (this.onSceneChange) {
      this.onSceneChange(scene);
    }
    
    // 更新窗口光效
    this.updateWindowLightEffect(scene);
  }

  private async updateWindowLightEffect(scene: TeachingScene): Promise<void> {
    try {
      const mainWindow = await window.getLastWindow();
      const ability = getContext(this) as unknown as EducationAbility;
      if (ability && ability.updateImmersiveLighting) {
        ability.updateImmersiveLighting(scene, this.learningState);
      }
    } catch (error) {
      console.error('Failed to update light effect:', error);
    }
  }

  private triggerHapticFeedback(): void {
    try {
      vibrator.startVibration({
        type: 'time',
        duration: 40
      }, {
        id: 0
      });
    } catch (error) {
      console.error('Haptic feedback failed:', error);
    }
  }

  // 内容构建器(由外部传入)
  @BuilderParam contentBuilder: () => void = this.defaultContentBuilder;

  @Builder
  defaultContentBuilder(): void {
    Column() {
      Text('教学内容区域')
        .fontSize(16)
        .fontColor('#999999')
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}

3.4 HMAF智能体服务层(EducationAgentService.ets)

代码亮点:本段代码实现了基于HMAF框架的四层智能体协作架构。通过AgentController注册学情采集、智能诊断、资源推荐、家校协同四个智能体,每个智能体通过FunctionComponent暴露工具能力。核心设计包括:智能体状态机管理(idle/running/completed/error)、A2A协议跨智能体任务委托、以及基于Intents Kit的意图感知调度。

// entry/src/main/ets/services/EducationAgentService.ets
import { 
  AgentController, 
  FunctionComponent, 
  FunctionController,
  AgentIntent 
} from '@kit.AgentFrameworkKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { distributedDeviceManager } from '@kit.DistributedServiceKit';

// 智能体类型枚举
export enum AgentType {
  LEARNING_COLLECTOR = 'learning_collector',  // 学情采集智能体
  SMART_DIAGNOSIS = 'smart_diagnosis',        // 智能诊断智能体
  RESOURCE_RECOMMENDER = 'resource_recommender', // 资源推荐智能体
  HOME_SCHOOL_BRIDGE = 'home_school_bridge'   // 家校协同智能体
}

// 智能体状态
export enum AgentStatus {
  IDLE = 'idle',
  RUNNING = 'running',
  COMPLETED = 'completed',
  ERROR = 'error'
}

// 学情数据接口
export interface LearningData {
  studentId: string;
  studentName: string;
  focusScore: number;        // 专注度评分 0-100
  participationRate: number; // 参与率 0-100
  comprehensionLevel: 'high' | 'medium' | 'low';
  weakPoints: string[];      // 薄弱知识点
  timestamp: number;
}

// 诊断结果接口
export interface DiagnosisResult {
  studentId: string;
  overallLevel: 'excellent' | 'good' | 'average' | 'poor';
  riskFactors: string[];
  suggestions: string[];
  recommendedResources: ResourceItem[];
}

// 资源项接口
export interface ResourceItem {
  resourceId: string;
  title: string;
  type: 'video' | 'document' | 'quiz' | 'interactive';
  difficulty: 'easy' | 'medium' | 'hard';
  matchScore: number;
  url: string;
}

// 家校消息接口
export interface HomeSchoolMessage {
  messageId: string;
  type: 'progress' | 'alert' | 'suggestion' | 'praise';
  studentId: string;
  parentId: string;
  content: string;
  actionRequired: boolean;
  timestamp: number;
}

export class EducationAgentService {
  private static instance: EducationAgentService;
  private agentController: AgentController | null = null;
  private agents: Map<AgentType, FunctionController> = new Map();
  private agentStatus: Map<AgentType, AgentStatus> = new Map();
  
  // 学情数据缓存
  private learningDataCache: Map<string, LearningData[]> = new Map();
  // 诊断结果缓存
  private diagnosisCache: Map<string, DiagnosisResult> = new Map();

  private constructor() {}

  static getInstance(): EducationAgentService {
    if (!EducationAgentService.instance) {
      EducationAgentService.instance = new EducationAgentService();
    }
    return EducationAgentService.instance;
  }

  // 初始化智能体框架
  async initialize(): Promise<void> {
    try {
      this.agentController = new AgentController({
        agentName: 'SmartEducationHub',
        agentDescription: '智教云枢 - 智慧教育AI智能体中枢',
        agentVersion: '1.0.0'
      });

      // 注册四个核心智能体
      await this.registerLearningCollector();
      await this.registerSmartDiagnosis();
      await this.registerResourceRecommender();
      await this.registerHomeSchoolBridge();

      hilog.info(0x0000, 'SmartEducation', 'All agents registered successfully');
    } catch (error) {
      hilog.error(0x0000, 'SmartEducation', 
        'Failed to initialize agent service: %{public}s', JSON.stringify(error));
      throw error;
    }
  }

  // 注册学情采集智能体
  private async registerLearningCollector(): Promise<void> {
    const collector = new FunctionController({
      functionName: 'collectLearningData',
      description: '实时采集学生课堂学情数据,包括专注度、参与率、理解程度等',
      parameters: {
        type: 'object',
        properties: {
          classId: { type: 'string', description: '班级ID' },
          subject: { type: 'string', description: '学科' },
          duration: { type: 'number', description: '采集时长(分钟)' }
        },
        required: ['classId', 'subject']
      }
    });

    // 实现学情采集逻辑
    collector.onCall(async (params: Record<string, Object>) => {
      this.agentStatus.set(AgentType.LEARNING_COLLECTOR, AgentStatus.RUNNING);
      
      try {
        const classId = params.classId as string;
        const subject = params.subject as string;
        
        // 模拟从分布式设备采集学情数据(实际应接入课堂IoT设备)
        const learningData = await this.collectFromDevices(classId, subject);
        
        // 缓存数据
        if (!this.learningDataCache.has(classId)) {
          this.learningDataCache.set(classId, []);
        }
        this.learningDataCache.get(classId)?.push(...learningData);
        
        this.agentStatus.set(AgentType.LEARNING_COLLECTOR, AgentStatus.COMPLETED);
        
        // 触发智能诊断(A2A协议:智能体间任务委托)
        await this.delegateToDiagnosis(classId);
        
        return {
          success: true,
          data: learningData,
          count: learningData.length
        };
      } catch (error) {
        this.agentStatus.set(AgentType.LEARNING_COLLECTOR, AgentStatus.ERROR);
        throw error;
      }
    });

    this.agents.set(AgentType.LEARNING_COLLECTOR, collector);
    await this.agentController?.registerFunction(collector);
  }

  // 注册智能诊断智能体
  private async registerSmartDiagnosis(): Promise<void> {
    const diagnosis = new FunctionController({
      functionName: 'diagnoseLearning',
      description: '基于学情数据进行智能诊断,识别薄弱知识点和学习风险',
      parameters: {
        type: 'object',
        properties: {
          classId: { type: 'string', description: '班级ID' },
          analysisType: { type: 'string', enum: ['individual', 'class'], description: '分析类型' }
        },
        required: ['classId']
      }
    });

    diagnosis.onCall(async (params: Record<string, Object>) => {
      this.agentStatus.set(AgentType.SMART_DIAGNOSIS, AgentStatus.RUNNING);
      
      try {
        const classId = params.classId as string;
        const data = this.learningDataCache.get(classId) || [];
        
        // 模拟AI诊断逻辑(实际应调用云端大模型API)
        const results: DiagnosisResult[] = data.map(item => ({
          studentId: item.studentId,
          overallLevel: this.calculateLevel(item.focusScore, item.participationRate),
          riskFactors: item.weakPoints,
          suggestions: this.generateSuggestions(item),
          recommendedResources: []
        }));
        
        results.forEach(r => this.diagnosisCache.set(r.studentId, r));
        this.agentStatus.set(AgentType.SMART_DIAGNOSIS, AgentStatus.COMPLETED);
        
        // 触发资源推荐(A2A协议)
        await this.delegateToRecommendation(classId);
        
        return { success: true, results };
      } catch (error) {
        this.agentStatus.set(AgentType.SMART_DIAGNOSIS, AgentStatus.ERROR);
        throw error;
      }
    });

    this.agents.set(AgentType.SMART_DIAGNOSIS, diagnosis);
    await this.agentController?.registerFunction(diagnosis);
  }

  // 注册资源推荐智能体
  private async registerResourceRecommender(): Promise<void> {
    const recommender = new FunctionController({
      functionName: 'recommendResources',
      description: '基于诊断结果为学生推荐个性化学习资源',
      parameters: {
        type: 'object',
        properties: {
          studentId: { type: 'string', description: '学生ID' },
          subject: { type: 'string', description: '学科' },
          limit: { type: 'number', description: '推荐数量' }
        },
        required: ['studentId', 'subject']
      }
    });

    recommender.onCall(async (params: Record<string, Object>) => {
      this.agentStatus.set(AgentType.RESOURCE_RECOMMENDER, AgentStatus.RUNNING);
      
      try {
        const studentId = params.studentId as string;
        const subject = params.subject as string;
        const limit = (params.limit as number) || 5;
        
        const diagnosis = this.diagnosisCache.get(studentId);
        if (!diagnosis) {
          throw new Error('No diagnosis data found for student');
        }
        
        // 模拟资源匹配算法
        const resources: ResourceItem[] = diagnosis.riskFactors.map((point, index) => ({
          resourceId: `res_${studentId}_${index}`,
          title: `${subject} - ${point}专项训练`,
          type: ['video', 'document', 'quiz', 'interactive'][index % 4] as ResourceItem['type'],
          difficulty: diagnosis.overallLevel === 'poor' ? 'easy' : 
                     diagnosis.overallLevel === 'average' ? 'medium' : 'hard',
          matchScore: 85 + Math.random() * 15,
          url: `https://edu-resource.harmonyos.com/${subject}/${point}`
        })).slice(0, limit);
        
        this.agentStatus.set(AgentType.RESOURCE_RECOMMENDER, AgentStatus.COMPLETED);
        return { success: true, resources };
      } catch (error) {
        this.agentStatus.set(AgentType.RESOURCE_RECOMMENDER, AgentStatus.ERROR);
        throw error;
      }
    });

    this.agents.set(AgentType.RESOURCE_RECOMMENDER, recommender);
    await this.agentController?.registerFunction(recommender);
  }

  // 注册家校协同智能体
  private async registerHomeSchoolBridge(): Promise<void> {
    const bridge = new FunctionController({
      functionName: 'sendHomeSchoolMessage',
      description: '向家长发送学情报告和协同建议',
      parameters: {
        type: 'object',
        properties: {
          studentId: { type: 'string', description: '学生ID' },
          messageType: { type: 'string', enum: ['progress', 'alert', 'suggestion', 'praise'] },
          customContent: { type: 'string', description: '自定义内容' }
        },
        required: ['studentId', 'messageType']
      }
    });

    bridge.onCall(async (params: Record<string, Object>) => {
      this.agentStatus.set(AgentType.HOME_SCHOOL_BRIDGE, AgentStatus.RUNNING);
      
      try {
        const studentId = params.studentId as string;
        const messageType = params.messageType as HomeSchoolMessage['type'];
        const diagnosis = this.diagnosisCache.get(studentId);
        
        const message: HomeSchoolMessage = {
          messageId: `msg_${Date.now()}`,
          type: messageType,
          studentId,
          parentId: `parent_${studentId}`,
          content: params.customContent as string || this.generateDefaultMessage(diagnosis, messageType),
          actionRequired: messageType === 'alert' || messageType === 'suggestion',
          timestamp: Date.now()
        };
        
        // 模拟发送消息(实际应调用分布式消息服务)
        await this.sendToParentDevice(message);
        
        this.agentStatus.set(AgentType.HOME_SCHOOL_BRIDGE, AgentStatus.COMPLETED);
        return { success: true, messageId: message.messageId };
      } catch (error) {
        this.agentStatus.set(AgentType.HOME_SCHOOL_BRIDGE, AgentStatus.ERROR);
        throw error;
      }
    });

    this.agents.set(AgentType.HOME_SCHOOL_BRIDGE, bridge);
    await this.agentController?.registerFunction(bridge);
  }

  // 从分布式设备采集学情数据
  private async collectFromDevices(classId: string, subject: string): Promise<LearningData[]> {
    // 获取分布式设备列表(学生平板、智能笔、答题器等)
    const devices = distributedDeviceManager.getAvailableDeviceListSync();
    
    // 模拟采集数据
    const mockData: LearningData[] = Array.from({ length: 30 }, (_, i) => ({
      studentId: `stu_${classId}_${i + 1}`,
      studentName: `学生${i + 1}`,
      focusScore: 60 + Math.random() * 40,
      participationRate: 50 + Math.random() * 50,
      comprehensionLevel: ['high', 'medium', 'low'][Math.floor(Math.random() * 3)] as LearningData['comprehensionLevel'],
      weakPoints: [`${subject}知识点${Math.floor(Math.random() * 10) + 1}`],
      timestamp: Date.now()
    }));
    
    return mockData;
  }

  // A2A协议:委托诊断任务
  private async delegateToDiagnosis(classId: string): Promise<void> {
    const diagnosisAgent = this.agents.get(AgentType.SMART_DIAGNOSIS);
    if (diagnosisAgent) {
      await diagnosisAgent.call({ classId, analysisType: 'class' });
    }
  }

  // A2A协议:委托推荐任务
  private async delegateToRecommendation(classId: string): Promise<void> {
    const students = this.learningDataCache.get(classId) || [];
    const recommender = this.agents.get(AgentType.RESOURCE_RECOMMENDER);
    
    for (const student of students.slice(0, 5)) { // 批量处理前5名学生
      if (recommender) {
        await recommender.call({ 
          studentId: student.studentId, 
          subject: '数学' 
        });
      }
    }
  }

  // 辅助方法
  private calculateLevel(focus: number, participation: number): DiagnosisResult['overallLevel'] {
    const avg = (focus + participation) / 2;
    if (avg >= 85) return 'excellent';
    if (avg >= 70) return 'good';
    if (avg >= 60) return 'average';
    return 'poor';
  }

  private generateSuggestions(data: LearningData): string[] {
    const suggestions: string[] = [];
    if (data.focusScore < 70) suggestions.push('建议增加课堂互动环节');
    if (data.participationRate < 60) suggestions.push('建议采用小组讨论形式');
    if (data.comprehensionLevel === 'low') suggestions.push('建议进行一对一辅导');
    return suggestions;
  }

  private generateDefaultMessage(diagnosis?: DiagnosisResult, type?: string): string {
    if (!diagnosis) return '暂无学情数据';
    switch (type) {
      case 'progress': return `${diagnosis.studentId}本周学习进度正常,继续保持`;
      case 'alert': return `${diagnosis.studentId}近期学习状态下滑,请关注`;
      case 'suggestion': return `建议为${diagnosis.studentId}安排${diagnosis.suggestions[0]}`;
      case 'praise': return `${diagnosis.studentId}本周表现优异,请给予鼓励`;
      default: return '学情更新';
    }
  }

  private async sendToParentDevice(message: HomeSchoolMessage): Promise<void> {
    // 实际应通过分布式消息服务发送到家长端设备
    hilog.info(0x0000, 'SmartEducation', 
      'Message sent to parent: %{public}s', JSON.stringify(message));
  }

  // 公共API:获取智能体状态
  getAgentStatus(type: AgentType): AgentStatus {
    return this.agentStatus.get(type) || AgentStatus.IDLE;
  }

  // 公共API:触发学情采集
  async triggerLearningCollection(classId: string, subject: string): Promise<LearningData[]> {
    const collector = this.agents.get(AgentType.LEARNING_COLLECTOR);
    if (!collector) throw new Error('Learning collector not registered');
    
    const result = await collector.call({ classId, subject });
    return (result as Record<string, Object>).data as LearningData[];
  }

  // 公共API:获取诊断结果
  getDiagnosisResult(studentId: string): DiagnosisResult | undefined {
    return this.diagnosisCache.get(studentId);
  }
}

3.5 课堂教学主页面(ClassroomPage.ets)

代码亮点:本页面实现了课堂教学场景的核心交互,包括:实时学情热力图(通过Canvas绘制学生座位图,颜色深浅表示专注度)、HMAF智能体状态实时面板(显示四个智能体的运行状态)、悬浮导航集成、以及基于沉浸光感的动态背景。

// entry/src/main/ets/pages/ClassroomPage.ets
import { EducationAgentService, LearningData, AgentType, AgentStatus } from '../services/EducationAgentService';
import { FloatTeachingNav, TeachingScene } from '../components/FloatTeachingNav';
import { LearningState } from '../abilities/EducationAbility';

@Entry
@Component
struct ClassroomPage {
  @State learningData: LearningData[] = [];
  @State isLoading: boolean = false;
  @State selectedStudent: LearningData | null = null;
  @State agentStatuses: Record<AgentType, AgentStatus> = {
    [AgentType.LEARNING_COLLECTOR]: AgentStatus.IDLE,
    [AgentType.SMART_DIAGNOSIS]: AgentStatus.IDLE,
    [AgentType.RESOURCE_RECOMMENDER]: AgentStatus.IDLE,
    [AgentType.HOME_SCHOOL_BRIDGE]: AgentStatus.IDLE
  };
  
  private agentService: EducationAgentService = EducationAgentService.getInstance();
  private classId: string = 'class_2026_01';
  private refreshTimer: number = -1;

  aboutToAppear(): void {
    this.initializeAgentService();
    this.startRealTimeMonitoring();
  }

  aboutToDisappear(): void {
    if (this.refreshTimer !== -1) {
      clearInterval(this.refreshTimer);
    }
  }

  private async initializeAgentService(): Promise<void> {
    try {
      await this.agentService.initialize();
      // 初始化学情采集
      await this.collectLearningData();
    } catch (error) {
      console.error('Failed to initialize:', error);
    }
  }

  private startRealTimeMonitoring(): void {
    // 每10秒刷新智能体状态
    this.refreshTimer = setInterval(() => {
      this.updateAgentStatuses();
    }, 10000);
  }

  private updateAgentStatuses(): void {
    this.agentStatuses = {
      [AgentType.LEARNING_COLLECTOR]: this.agentService.getAgentStatus(AgentType.LEARNING_COLLECTOR),
      [AgentType.SMART_DIAGNOSIS]: this.agentService.getAgentStatus(AgentType.SMART_DIAGNOSIS),
      [AgentType.RESOURCE_RECOMMENDER]: this.agentService.getAgentStatus(AgentType.RESOURCE_RECOMMENDER),
      [AgentType.HOME_SCHOOL_BRIDGE]: this.agentService.getAgentStatus(AgentType.HOME_SCHOOL_BRIDGE)
    };
  }

  private async collectLearningData(): Promise<void> {
    this.isLoading = true;
    try {
      const data = await this.agentService.triggerLearningCollection(this.classId, '数学');
      this.learningData = data;
    } catch (error) {
      console.error('Failed to collect data:', error);
    } finally {
      this.isLoading = false;
    }
  }

  build() {
    FloatTeachingNav({
      currentScene: TeachingScene.CLASSROOM,
      onSceneChange: (scene: TeachingScene) => {
        // 场景切换逻辑
        console.info(`Switched to scene: ${scene}`);
      }
    }) {
      this.classroomContentBuilder()
    }
  }

  @Builder
  classroomContentBuilder(): void {
    Column() {
      // 顶部标题栏(沉浸光感安全区适配)
      Row() {
        Column() {
          Text('三年级(2)班 - 数学课堂')
            .fontSize(24)
            .fontWeight(FontWeight.Bold)
            .fontColor('#1A1A1A')
          
          Text(`实时学情 | 共${this.learningData.length}人 | 平均专注度: ${this.getAverageFocus()}%`)
            .fontSize(14)
            .fontColor('#666666')
            .margin({ top: 4 })
        }
        .alignItems(HorizontalAlign.Start)
        .layoutWeight(1)

        // 智能体状态指示器
        this.agentStatusIndicator()
      }
      .width('100%')
      .height(80)
      .padding({ left: 24, right: 24, top: 16 })
      .backgroundColor('rgba(255,255,255,0.8)')
      .backdropFilter($r('sys.blur.10'))

      // 学情热力图区域
      Stack() {
        if (this.isLoading) {
          LoadingProgress()
            .width(48)
            .height(48)
            .color('#2196F3')
        } else {
          this.learningHeatmapBuilder()
        }
      }
      .width('100%')
      .layoutWeight(1)
      .padding(16)

      // 选中学生详情面板
      if (this.selectedStudent) {
        this.studentDetailPanel()
      }
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#F5F7FA')
  }

  // 学情热力图构建器
  @Builder
  learningHeatmapBuilder(): void {
    Grid() {
      ForEach(this.learningData, (student: LearningData) => {
        GridItem() {
          Column() {
            Text(student.studentName)
              .fontSize(13)
              .fontColor('#FFFFFF')
              .fontWeight(FontWeight.Medium)
            
            Text(`${Math.round(student.focusScore)}%`)
              .fontSize(11)
              .fontColor('rgba(255,255,255,0.9)')
              .margin({ top: 2 })
          }
          .width('100%')
          .height('100%')
          .justifyContent(FlexAlign.Center)
          .backgroundColor(this.getFocusColor(student.focusScore))
          .borderRadius(12)
          .shadow({
            radius: 8,
            color: 'rgba(0,0,0,0.1)',
            offsetX: 0,
            offsetY: 2
          })
          .scale({ x: this.selectedStudent?.studentId === student.studentId ? 1.05 : 1.0, y: this.selectedStudent?.studentId === student.studentId ? 1.05 : 1.0 })
          .animation({
            duration: 200,
            curve: Curve.EaseInOut
          })
        }
        .onClick(() => {
          this.selectedStudent = this.selectedStudent?.studentId === student.studentId ? null : student;
        })
      })
    }
    .columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr')
    .rowsTemplate('1fr 1fr 1fr 1fr 1fr')
    .columnsGap(8)
    .rowsGap(8)
    .width('100%')
    .height('100%')
  }

  // 学生详情面板
  @Builder
  studentDetailPanel(): void {
    Column() {
      Row() {
        Text(this.selectedStudent!.studentName)
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
          .fontColor('#1A1A1A')
        
        Button('关闭')
          .fontSize(12)
          .fontColor('#666666')
          .backgroundColor('transparent')
          .onClick(() => {
            this.selectedStudent = null;
          })
      }
      .width('100%')
      .justifyContent(FlexAlign.SpaceBetween)

      // 学情指标
      this.metricBar('专注度', this.selectedStudent!.focusScore, '#2196F3')
      this.metricBar('参与率', this.selectedStudent!.participationRate, '#4CAF50')
      
      // 薄弱知识点
      Text('薄弱知识点')
        .fontSize(14)
        .fontColor('#666666')
        .margin({ top: 12, bottom: 8 })
        .alignSelf(ItemAlign.Start)

      Row() {
        ForEach(this.selectedStudent!.weakPoints, (point: string) => {
          Text(point)
            .fontSize(12)
            .fontColor('#FF5252')
            .backgroundColor('rgba(255,82,82,0.1)')
            .padding({ left: 8, right: 8, top: 4, bottom: 4 })
            .borderRadius(8)
            .margin({ right: 8 })
        })
      }
      .width('100%')
      .margin({ bottom: 12 })

      // 智能体操作按钮
      Row() {
        Button('智能诊断')
          .fontSize(13)
          .fontColor('#FFFFFF')
          .backgroundColor('#2196F3')
          .borderRadius(20)
          .padding({ left: 16, right: 16 })
          .onClick(() => {
            this.triggerDiagnosis(this.selectedStudent!.studentId);
          })

        Button('推荐资源')
          .fontSize(13)
          .fontColor('#FFFFFF')
          .backgroundColor('#4CAF50')
          .borderRadius(20)
          .padding({ left: 16, right: 16 })
          .margin({ left: 12 })
          .onClick(() => {
            this.triggerRecommendation(this.selectedStudent!.studentId);
          })

        Button('通知家长')
          .fontSize(13)
          .fontColor('#FFFFFF')
          .backgroundColor('#FF9800')
          .borderRadius(20)
          .padding({ left: 16, right: 16 })
          .margin({ left: 12 })
          .onClick(() => {
            this.notifyParent(this.selectedStudent!.studentId);
          })
      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
    }
    .width('100%')
    .height(280)
    .padding(20)
    .backgroundColor('rgba(255,255,255,0.95)')
    .backdropFilter($r('sys.blur.20'))
    .borderRadius({ topLeft: 24, topRight: 24 })
    .shadow({
      radius: 16,
      color: 'rgba(0,0,0,0.1)',
      offsetX: 0,
      offsetY: -4
    })
    .animation({
      duration: 300,
      curve: Curve.Spring
    })
  }

  // 智能体状态指示器
  @Builder
  agentStatusIndicator(): void {
    Row() {
      ForEach(Object.entries(this.agentStatuses), ([type, status]: [string, AgentStatus]) => {
        Column() {
          Circle()
            .width(8)
            .height(8)
            .fill(this.getStatusColor(status))
            .shadow({
              radius: 4,
              color: this.getStatusColor(status, 0.4),
              offsetX: 0,
              offsetY: 0
            })
          
          Text(this.getAgentShortName(type as AgentType))
            .fontSize(9)
            .fontColor('#999999')
            .margin({ top: 2 })
        }
        .margin({ left: 8 })
      })
    }
  }

  // 指标条构建器
  @Builder
  metricBar(label: string, value: number, color: string): void {
    Row() {
      Text(label)
        .fontSize(13)
        .fontColor('#666666')
        .width(60)
      
      Stack() {
        Row()
          .width('100%')
          .height(8)
          .backgroundColor('rgba(0,0,0,0.05)')
          .borderRadius(4)
        
        Row()
          .width(`${value}%`)
          .height(8)
          .backgroundColor(color)
          .borderRadius(4)
          .animation({
            duration: 1000,
            curve: Curve.EaseOut
          })
      }
      .layoutWeight(1)
      .height(8)
      
      Text(`${Math.round(value)}%`)
        .fontSize(13)
        .fontColor(color)
        .width(40)
        .textAlign(TextAlign.End)
    }
    .width('100%')
    .height(32)
    .alignItems(VerticalAlign.Center)
  }

  // 根据专注度获取颜色
  private getFocusColor(score: number): string {
    if (score >= 85) return '#4CAF50';
    if (score >= 70) return '#8BC34A';
    if (score >= 60) return '#FFC107';
    if (score >= 40) return '#FF9800';
    return '#FF5252';
  }

  // 获取平均专注度
  private getAverageFocus(): number {
    if (this.learningData.length === 0) return 0;
    const sum = this.learningData.reduce((acc, cur) => acc + cur.focusScore, 0);
    return Math.round(sum / this.learningData.length);
  }

  // 获取智能体状态颜色
  private getStatusColor(status: AgentStatus, alpha?: number): string {
    const colors: Record<AgentStatus, string> = {
      [AgentStatus.IDLE]: '#9E9E9E',
      [AgentStatus.RUNNING]: '#2196F3',
      [AgentStatus.COMPLETED]: '#4CAF50',
      [AgentStatus.ERROR]: '#FF5252'
    };
    const baseColor = colors[status];
    if (alpha !== undefined) {
      return baseColor + Math.round(alpha * 255).toString(16).padStart(2, '0');
    }
    return baseColor;
  }

  // 获取智能体简称
  private getAgentShortName(type: AgentType): string {
    const names: Record<AgentType, string> = {
      [AgentType.LEARNING_COLLECTOR]: '采集',
      [AgentType.SMART_DIAGNOSIS]: '诊断',
      [AgentType.RESOURCE_RECOMMENDER]: '推荐',
      [AgentType.HOME_SCHOOL_BRIDGE]: '家校'
    };
    return names[type];
  }

  // 触发智能诊断
  private async triggerDiagnosis(studentId: string): Promise<void> {
    const diagnosis = this.agentService.getDiagnosisResult(studentId);
    if (diagnosis) {
      console.info(`Diagnosis for ${studentId}:`, JSON.stringify(diagnosis));
    }
  }

  // 触发资源推荐
  private async triggerRecommendation(studentId: string): Promise<void> {
    const recommender = this.agentService['agents'].get(AgentType.RESOURCE_RECOMMENDER);
    if (recommender) {
      await recommender.call({ studentId, subject: '数学' });
    }
  }

  // 通知家长
  private async notifyParent(studentId: string): Promise<void> {
    const bridge = this.agentService['agents'].get(AgentType.HOME_SCHOOL_BRIDGE);
    if (bridge) {
      await bridge.call({ studentId, messageType: 'alert' });
    }
  }
}

3.6 浮动学情面板Ability(StudentPanelAbility.ets)

代码亮点:本Ability实现了HarmonyOS PC端的多窗口浮动面板,通过WindowStage.createSubWindow创建悬浮窗口,支持拖拽调整位置、实时显示学情数据、以及与主窗口的光效联动。

// entry/src/main/ets/abilities/StudentPanelAbility.ets
import { UIAbility, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';

export default class StudentPanelAbility extends UIAbility {
  private subWindow: window.Window | null = null;

  onWindowStageCreate(windowStage: window.WindowStage): void {
    hilog.info(0x0000, 'SmartEducation', 'StudentPanelAbility onWindowStageCreate');
    
    // 创建子窗口(浮动面板)
    this.createFloatingPanel(windowStage);
  }

  private async createFloatingPanel(windowStage: window.WindowStage): Promise<void> {
    try {
      // 创建子窗口
      this.subWindow = await windowStage.createSubWindow('studentPanel');
      
      // 设置窗口大小和位置(PC端右侧浮动)
      await this.subWindow.resize(360, 600);
      await this.subWindow.moveWindowTo(1200, 100);
      
      // 设置窗口属性
      await this.subWindow.setWindowLayoutFullScreen(true);
      await this.subWindow.setWindowBackgroundColor('rgba(255,255,255,0.92)');
      
      // 加载面板内容
      await this.subWindow.setUIContent('pages/StudentPanelPage');
      
      // 显示窗口
      await this.subWindow.showWindow();
      
      hilog.info(0x0000, 'SmartEducation', 'Floating panel created successfully');
    } catch (error) {
      hilog.error(0x0000, 'SmartEducation', 
        'Failed to create floating panel: %{public}s', JSON.stringify(error));
    }
  }

  onDestroy(): void {
    if (this.subWindow) {
      this.subWindow.destroyWindow();
      this.subWindow = null;
    }
  }
}

3.7 浮动学情面板页面(StudentPanelPage.ets)

// entry/src/main/ets/pages/StudentPanelPage.ets
import { EducationAgentService, LearningData } from '../services/EducationAgentService';

@Entry
@Component
struct StudentPanelPage {
  @State learningData: LearningData[] = [];
  @State sortBy: 'focus' | 'participation' | 'comprehension' = 'focus';
  private agentService: EducationAgentService = EducationAgentService.getInstance();

  aboutToAppear(): void {
    this.loadData();
    // 每5秒刷新数据
    setInterval(() => this.loadData(), 5000);
  }

  private async loadData(): Promise<void> {
    // 从主Ability获取数据(实际应通过分布式数据服务)
    this.learningData = [
      {
        studentId: 'stu_001',
        studentName: '张小明',
        focusScore: 92,
        participationRate: 88,
        comprehensionLevel: 'high',
        weakPoints: ['分数运算'],
        timestamp: Date.now()
      },
      {
        studentId: 'stu_002',
        studentName: '李小红',
        focusScore: 65,
        participationRate: 72,
        comprehensionLevel: 'medium',
        weakPoints: ['几何图形', '应用题'],
        timestamp: Date.now()
      },
      {
        studentId: 'stu_003',
        studentName: '王小强',
        focusScore: 45,
        participationRate: 38,
        comprehensionLevel: 'low',
        weakPoints: ['基础运算', '单位换算', '应用题'],
        timestamp: Date.now()
      }
    ];
  }

  build() {
    Column() {
      // 面板标题
      Row() {
        Text('实时学情面板')
          .fontSize(16)
          .fontWeight(FontWeight.Bold)
          .fontColor('#1A1A1A')
        
        Row() {
          Text('排序')
            .fontSize(12)
            .fontColor('#666666')
          
          Select([
            { value: '专注度', icon: $r('app.media.ic_sort') },
            { value: '参与率', icon: $r('app.media.ic_sort') },
            { value: '理解度', icon: $r('app.media.ic_sort') }
          ])
            .selected(0)
            .font({ size: 12 })
            .onSelect((index: number) => {
              const sorts: Array<'focus' | 'participation' | 'comprehension'> = ['focus', 'participation', 'comprehension'];
              this.sortBy = sorts[index];
            })
        }
      }
      .width('100%')
      .height(48)
      .padding({ left: 16, right: 16 })
      .justifyContent(FlexAlign.SpaceBetween)

      // 学情列表
      List() {
        ForEach(this.getSortedData(), (student: LearningData) => {
          ListItem() {
            this.studentCard(student)
          }
        })
      }
      .width('100%')
      .layoutWeight(1)
      .divider({ strokeWidth: 1, color: 'rgba(0,0,0,0.05)' })

      // 底部统计
      Row() {
        Text(`需关注: ${this.learningData.filter(s => s.focusScore < 60).length}`)
          .fontSize(12)
          .fontColor('#FF5252')
        
        Text(`表现优异: ${this.learningData.filter(s => s.focusScore >= 85).length}`)
          .fontSize(12)
          .fontColor('#4CAF50')
          .margin({ left: 16 })
      }
      .width('100%')
      .height(40)
      .padding({ left: 16, right: 16 })
      .backgroundColor('rgba(0,0,0,0.02)')
    }
    .width('100%')
    .height('100%')
    .backgroundColor('rgba(255,255,255,0.92)')
    .backdropFilter($r('sys.blur.20'))
  }

  @Builder
  studentCard(student: LearningData): void {
    Row() {
      Column() {
        Text(student.studentName)
          .fontSize(14)
          .fontWeight(FontWeight.Medium)
          .fontColor('#1A1A1A')
        
        Text(`薄弱: ${student.weakPoints.join(', ')}`)
          .fontSize(11)
          .fontColor('#999999')
          .margin({ top: 2 })
          .maxLines(1)
          .textOverflow({ overflow: TextOverflow.Ellipsis })
      }
      .alignItems(HorizontalAlign.Start)
      .layoutWeight(1)

      // 专注度环形指示器
      Stack() {
        Circle()
          .width(40)
          .height(40)
          .fill('transparent')
          .stroke('rgba(0,0,0,0.1)')
          .strokeWidth(4)
        
        Circle()
          .width(40)
          .height(40)
          .fill('transparent')
          .stroke(this.getFocusColor(student.focusScore))
          .strokeWidth(4)
          .strokeDashArray([student.focusScore / 100 * 125, 125])
          .strokeLineCap(LineCapStyle.Round)
          .rotate({ angle: -90, centerX: '50%', centerY: '50%' })
        
        Text(`${Math.round(student.focusScore)}`)
          .fontSize(12)
          .fontWeight(FontWeight.Bold)
          .fontColor(this.getFocusColor(student.focusScore))
      }
      .width(40)
      .height(40)
    }
    .width('100%')
    .height(64)
    .padding({ left: 16, right: 16 })
    .backgroundColor(student.focusScore < 60 ? 'rgba(255,82,82,0.05)' : 'transparent')
  }

  private getSortedData(): LearningData[] {
    return [...this.learningData].sort((a, b) => {
      switch (this.sortBy) {
        case 'focus': return b.focusScore - a.focusScore;
        case 'participation': return b.participationRate - a.participationRate;
        case 'comprehension': 
          const levels = { high: 3, medium: 2, low: 1 };
          return levels[b.comprehensionLevel] - levels[a.comprehensionLevel];
        default: return 0;
      }
    });
  }

  private getFocusColor(score: number): string {
    if (score >= 85) return '#4CAF50';
    if (score >= 60) return '#FFC107';
    return '#FF5252';
  }
}

四、关键技术总结

4.1 悬浮导航适配清单

适配项 实现方式 注意事项
安全区避让 window.getWindowAvoidArea()获取导航栏高度 PC端需额外考虑窗口标题栏高度
透明度调节 Slider组件+三档枚举(85%/70%/55%) 建议默认使用BALANCED档位
玻璃拟态效果 backgroundBlurStyle(BlurStyle.REGULAR)+backdropFilter 需开启硬件加速
手势冲突处理 LongPressGesture触发扩展菜单 避免与系统全面屏手势冲突
智能体徽章 Badge组件+动态状态指示 红色表示告警,绿色表示运行中

4.2 沉浸光感最佳实践

  1. 场景化光效映射:建立教学场景×学情状态的光效矩阵,避免色彩过于跳跃
  2. P3广色域适配:使用系统提供的色值常量(如$r('sys.color.brand'))确保跨设备一致性
  3. 动态过渡动画:光效切换使用Curve.Spring曲线,时长控制在300-500ms
  4. 系统级同步:通过setSystemBarProperties实现状态栏、导航栏光效联动
  5. 无障碍适配:为色盲用户提供纹理/图标辅助识别

4.3 HMAF智能体架构设计原则

  1. 单一职责:每个智能体只负责一个教育环节(采集/诊断/推荐/协同)
  2. 状态机管理:明确idle/running/completed/error四种状态,避免竞态条件
  3. A2A协议通信:智能体间通过FunctionController.call()进行任务委托,而非直接调用
  4. 分布式感知:利用distributedDeviceManager获取课堂IoT设备数据
  5. 意图驱动:通过Intents Kit理解教师自然语言指令,自动触发对应智能体

五、调试与测试建议

5.1 DevEco Studio调试配置

// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "SmartEducation PC Debug",
      "type": "harmonyos",
      "request": "launch",
      "deviceType": "2in1",  // PC/平板二合一设备
      "moduleName": "entry",
      "abilityName": "EducationAbility",
      "immersiveMode": true,  // 启用沉浸模式调试
      "agentFrameworkDebug": true  // 启用HMAF调试日志
    }
  ]
}

在这里插入图片描述

5.2 关键测试场景

测试场景 测试内容 预期结果
悬浮导航交互 长按展开/收起、透明度调节、场景切换 动画流畅,无卡顿,安全区避让正确
沉浸光效同步 切换教学场景、学情状态变化 窗口背景、状态栏、导航栏光效一致变化
HMAF智能体协作 触发学情采集→自动诊断→资源推荐链路 四个智能体状态正确流转,A2A委托无死锁
多窗口协作 主窗口+浮动学情面板+课堂视窗 窗口间数据同步,光效联动,拖拽流畅
分布式设备 连接学生平板、智能笔等IoT设备 设备发现正常,学情数据实时采集

六、结语

本文通过"智教云枢"智慧教育综合管理平台的实战开发,展示了HarmonyOS 6(API 23)三大核心特性在PC端教育场景的深度应用:

  • 悬浮导航实现了教学场景的快速切换与智能体状态的直观感知
  • 沉浸光感将抽象的学情数据转化为直观的视觉氛围,实现"学情即光效"
  • HMAF框架构建了"采集-诊断-推荐-协同"四层智能体协作架构,实现教育管理的智能化升级

随着HarmonyOS生态的持续繁荣(应用与元服务数量已突破35万+,注册开发者达800万+), 基于HMAF的智能体应用将成为鸿蒙PC应用开发的重要方向。期待更多开发者加入鸿蒙生态,共同推动智慧教育的技术创新。


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

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐