HarmonyOS5 运动健康app(三):健康睡眠(附代码)

2025-06-28 20:07:12
111次阅读
0个评论

image.png

智能睡眠监测应用架构设计文档

一、数据模型设计

1. 睡眠阶段枚举

enum SleepStageType {
  AWAKE = 'awake',   // 清醒状态
  LIGHT = 'light',   // 浅度睡眠
  DEEP = 'deep'      // 深度睡眠
}

2. 阶段配置接口

interface SleepSTyeS {
  icon: string;          // 阶段图标资源
  title: string;         // 阶段显示名称
  color: string;         // 主题色值
  minDuration: number;   // 最小持续时间(秒)
  maxDuration: number;   // 最大持续时间(秒)
  transitionChance: number // 状态转换概率
}

3. 睡眠记录结构

interface SleepRecord {
  id: string;            // 记录唯一ID
  startTime: Date;       // 开始时间
  endTime: Date;         // 结束时间
  duration: string;      // 总睡眠时长
  stages: SleepStage[];  // 阶段详细数据
  qualityScore: number;  // 质量评分(0-100)
}

二、核心状态管理

主要状态变量

@State isSleeping: boolean = false      // 睡眠状态标识
@State currentStage: SleepStageType     // 当前睡眠阶段
@State sleepDuration: string = "0时0分0秒" // 实时睡眠时长
@State sleepStages: SleepStage[] = []   // 阶段记录集合
@State sleepRecords: SleepRecord[] = [] // 历史记录存储

阶段配置数据

private stageConfig = {
  [SleepStageType.AWAKE]: {
    icon: "$r('app.media.awake_sleep_icon')",
    title: "清醒睡眠",
    color: "#e74c3c",
    minDuration: 30,
    maxDuration: 180,
    transitionChance: 0.7
  },
  // 其他阶段配置...
}

三、核心业务逻辑

1. 睡眠状态控制

// 开始睡眠监测
startSleep() {
  this.timerId = setInterval(() => {
    this.updateSleepDuration();
    this.checkStageTransition();
  }, 1000);
}

// 结束睡眠监测
endSleep() {
  clearInterval(this.timerId);
  this.generateSleepRecord();
}

2. 阶段自动转换算法

checkStageTransition() {
  const config = this.stageConfig[this.currentStage];
  
  // 强制转换条件
  if (this.currentStageDuration >= config.maxDuration) {
    this.transitionToNextStage();
  } 
  // 概率转换条件
  else if (this.currentStageDuration >= config.minDuration && 
           Math.random() < config.transitionChance) {
    this.transitionToNextStage();
  }
}

3. 睡眠质量评估体系

calculateQualityScore(): number {
  let score = 50; // 基础分
  
  // 深度睡眠加分
  const deepPercentage = this.getStagePercentage(SleepStageType.DEEP);
  score += this.clampScore(deepPercentage - 30, 20);
  
  // 清醒状态减分
  const awakePercentage = this.getStagePercentage(SleepStageType.AWAKE);
  score -= this.clampScore((awakePercentage - 10) * 2, 30);
  
  // 周期完整性加分
  score += Math.min(10, Math.floor(this.sleepStages.length / 3) * 2);
  
  return Math.max(0, Math.min(100, score));
}

四、UI组件设计

1. 状态主卡片

Stack() {
  // 动态背景圆环
  Circle()
    .fill(this.isSleeping ? '#3498db' : '#4682b4')
    .width(200).height(200);
  
  // 核心数据展示
  Column() {
    Text(this.sleepDuration)  // 实时时长
    Text(`当前: ${this.currentStageTitle}`) // 阶段状态
  }
}

2. 阶段分析面板

ForEach(this.sleepStages, (stage) => {
  Column() {
    Image(stage.icon)      // 阶段图标
    Text(stage.duration)   // 持续时间
    Text(stage.percentage) // 占比数据
  }
  .backgroundColor(stage.color + '10')
})

3. 质量评分组件

Column() {
  Text(`睡眠质量评分: ${score}/100`)
  Text(this.getQualityDescription(score)) // 文字评价
}

五、关键算法实现

1. 阶段持续时间计算

calculateDuration(start: Date, end: Date): string {
  const diff = end.getTime() - start.getTime();
  const hours = Math.floor(diff / 3600000);
  const minutes = Math.floor((diff % 3600000) / 60000);
  const seconds = Math.floor((diff % 60000) / 1000);
  return `${hours}时${minutes}分${seconds}秒`;
}

2. 阶段占比分析

calculateStagePercentages() {
  const totalSeconds = this.getTotalSeconds();
  this.sleepStages.forEach(stage => {
    const stageSeconds = (stage.endTime - stage.startTime) / 1000;
    stage.percentage = `${Math.round(stageSeconds / totalSeconds * 100)}%`;
  });
}

六、完整代码结构

点击查看完整实现
@Entry
@Component
struct SleepMonitor {
  // 状态管理
  @State isSleeping: boolean = false;
  @State currentStage: SleepStageType = SleepStageType.LIGHT;
  
  // 数据模型
  private stageConfig: Record<SleepStageType, SleepSTyeS> = { ... };
  
  // 业务逻辑
  private startSleep() { ... }
  private endSleep() { ... }
  private checkStageTransition() { ... }
  
  // UI组件
  @Builder SleepStatusCard() { ... }
  @Builder StageAnalysisPanel() { ... }

  build() {
    Column() {
      this.SleepStatusCard()
      this.StageAnalysisPanel()
    }
  }
}

七、数据流转示意图

[用户操作]
  ├─ 开始睡眠 → 启动计时器 → 实时更新阶段数据
  │    ├─ 每1秒检查阶段转换条件
  │    └─ 记录阶段变化时间点
  │
  └─ 结束睡眠 → 生成完整记录 → 计算质量评分
       ├─ 持久化存储历史数据
       └─ 更新可视化分析面板
收藏00

登录 后评论。没有帐号? 注册 一个。