下面我将展示如何利用CodeGenie从零开始构建一个完整的鸿蒙应用——智慧环境监测中心。该应用能够实时监控室内环境质量,提供健康建议和自动化控制。
应用功能概览
- 环境数据监控(温湿度、空气质量、光照强度)
- 健康分析报告(基于环境数据的健康评分)
- 自动化控制(智能联动空气净化器、空调等设备)
- 历史数据分析(环境变化趋势图表)
- 异常告警系统(环境异常即时通知)
开发过程记录
1. 创建项目基础结构
在DevEco Studio中告诉CodeGenie:
"创建一个鸿蒙应用,名为EcoMonitor,使用深绿色主题,包含主页、数据分析和设置三个页面"
CodeGenie生成响应:
// app.ets - 主入口
@Entry
@Component
struct EcoMonitor {
@State currentIndex: number = 0
private controller: TabsController = new TabsController()
build() {
Column() {
Tabs({ index: this.currentIndex, controller: this.controller }) {
TabContent() {
HomePage() // 主页
}
.tabBar('首页')
TabContent() {
AnalyticsPage() // 数据分析页
}
.tabBar('分析')
TabContent() {
SettingsPage() // 设置页
}
.tabBar('设置')
}
}
.width('100%')
.height('100%')
.backgroundColor('#f5f9f2')
}
}
2. 生成主页实时监控UI
"创建主页布局:顶部显示当前环境评分,中间显示环状数据仪表盘(温度、湿度、PM2.5),底部为设备控制区"
CodeGenie生成响应:
// HomePage.ets
@Component
struct HomePage {
@State temp: number = 25.6
@State humidity: number = 58
@State pm25: number = 24
@State score: number = 87
build() {
Column() {
// 健康评分卡片
HealthScoreCard(score: this.score)
// 环境数据仪表盘
Row({ space: 15 }) {
EnvironmentGauge(value: this.temp, type: 'temperature')
EnvironmentGauge(value: this.humidity, type: 'humidity')
EnvironmentGauge(value: this.pm25, type: 'pm25')
}.margin({ top: 20, bottom: 20 })
// 设备控制区
DeviceControlPanel()
}
}
}
@Component
private struct EnvironmentGauge {
@Prop value: number
private type: string
build() {
Column() {
Circle()
.width(100)
.height(100)
.fill(GaugeUtils.getFillColor(this.type, this.value))
.stroke(GaugeUtils.getStrokeColor(this.type, this.value))
.strokeWidth(8)
Text(`${Math.round(this.value)}`)
.fontSize(24)
.fontWeight(FontWeight.Bold)
Text(GaugeUtils.getLabel(this.type))
.fontSize(14)
.opacity(0.8)
}
}
}
3. 实现实时数据监控
"添加环境传感器数据读取功能:使用鸿蒙传感器API获取温湿度、光照和空气质量数据,并实时更新UI"
CodeGenie生成响应:
import sensor from '@ohos.sensor';
@Component
struct HomePage {
// ...原有状态变量...
aboutToAppear() {
// 注册温湿度传感器
sensor.on(sensor.SensorType.SENSOR_TYPE_TEMPERATURE, (data) => {
this.temp = data.temperature;
});
// 注册湿度传感器
sensor.on(sensor.SensorType.SENSOR_TYPE_HUMIDITY, (data) => {
this.humidity = data.humidity;
});
// 注册光感传感器
sensor.on(sensor.SensorType.SENSOR_TYPE_LIGHT, (data) => {
this.lightLevel = data.intensity;
this.calculateScore();
});
// 注册PM2.5传感器
sensor.on(sensor.SensorType.SENSOR_TYPE_PM2_5, (data) => {
this.pm25 = data.pm2_5;
this.calculateScore();
});
}
private calculateScore() {
// 计算环境健康评分算法
this.score = HealthAlgorithm.calculateScore(
this.temp,
this.humidity,
this.pm25,
this.lightLevel
);
}
}
4. 创建健康分析算法
"生成健康评分算法:根据环境参数计算健康分数(0-100分),温度20-25℃最优,湿度40-60%最优,PM2.5<35最优"
CodeGenie生成响应:
// HealthAlgorithm.ts
export class HealthAlgorithm {
static calculateScore(
temp: number,
humidity: number,
pm25: number,
light: number
): number {
// 温度评分(最佳区间20-25℃)
const tempScore = this.calcFactorScore(temp,
{ idealMin: 20, idealMax: 25, min: 15, max: 30 });
// 湿度评分(最佳区间40-60%)
const humidScore = this.calcFactorScore(humidity,
{ idealMin: 40, idealMax: 60, min: 30, max: 80 });
// PM2.5评分(值越低越好)
const pm25Score = this.calcLinearScore(pm25,
{ maxIdeal: 35, maxAcceptable: 75 });
// 光照评分(合理区间150-300 lux)
const lightScore = this.calcFactorScore(light,
{ idealMin: 150, idealMax: 300, min: 50, max: 1000 });
// 加权计算总分
return Math.round(
tempScore * 0.25 +
humidScore * 0.2 +
pm25Score * 0.4 +
lightScore * 0.15
);
}
private static calcFactorScore(value: number,
range: { idealMin: number, idealMax: number, min: number, max: number }): number {
if (value < range.min) return 0;
if (value > range.max) return 0;
if (value >= range.idealMin && value <= range.idealMax) return 100;
// 在合理区间但不是理想区间,分数递减
if (value < range.idealMin) {
return (value - range.min) / (range.idealMin - range.min) * 100;
} else {
return 100 - (value - range.idealMax) / (range.max - range.idealMax) * 100;
}
}
}
5. 设备控制面板实现
"创建设备控制面板:包含空调开关+温度调节、空气净化器开关、加湿器开关,使用滑块控制"
CodeGenie生成响应:
@Component
struct DeviceControlPanel {
@State acOn: boolean = false
@State acTemp: number = 24
@State purifierOn: boolean = true
@State humidifierOn: boolean = false
build() {
Column() {
// 空调控制
Row() {
Toggle({ type: ToggleType.Switch, isOn: this.acOn })
.onChange(isOn => this.toggleDevice('ac', isOn))
Text('空调').fontSize(16).layoutWeight(1)
Slider({ value: this.acTemp, min: 16, max: 30, style: SliderStyle.OutSet })
.onChange(value => this.adjustAcTemp(value))
.enabled(this.acOn)
.width('60%')
}.padding(10)
// 空气净化器控制
DeviceToggleSwitch(
state: this.purifierOn,
label: '空气净化器',
icon: $r('app.media.air_purifier'),
onChange: (isOn) => this.toggleDevice('purifier', isOn)
)
// 加湿器控制
DeviceToggleSwitch(
state: this.humidifierOn,
label: '加湿器',
icon: $r('app.media.humidifier'),
onChange: (isOn) => this.toggleDevice('humidifier', isOn)
)
}
}
private toggleDevice(device: string, state: boolean) {
// 发送设备控制命令
DeviceControlService.controlDevice(device, { power: state });
}
private adjustAcTemp(temp: number) {
DeviceControlService.controlDevice('ac', { temperature: temp });
}
}
6. 数据可视化页面
"创建数据分析页面:显示环境数据随时间变化的折线图,可选择时间范围(24小时/7天/30天)"
CodeGenie生成响应:
@Component
struct AnalyticsPage {
@State timeRange: string = '24h'
@State chartData: LineData = new LineData()
build() {
Column() {
// 时间范围选择器
TimeRangeSelector(current: this.timeRange,
onChange: (range) => this.loadChartData(range))
// 数据图表
LineChart({
data: this.chartData,
maxPoints: this.getMaxPoints(),
height: 300,
colors: ['#2ecc71', '#3498db', '#9b59b6']
})
.margin({ top: 20 })
// 数据说明
DataLegend(items: [
{ name: '温度', color: '#2ecc71', unit: '℃' },
{ name: '湿度', color: '#3498db', unit: '%' },
{ name: 'PM2.5', color: '#9b59b6', unit: 'μg/m³' }
])
}
}
private loadChartData(range: string) {
this.timeRange = range;
// 加载数据逻辑...
}
private getMaxPoints(): number {
switch (this.timeRange) {
case '24h': return 24; // 每小时一个点
case '7d': return 28; // 每6小时一个点
case '30d': return 30; // 每天一个点
}
return 24;
}
}
7. 异常告警系统
"添加异常告警功能:当温度超过30℃、PM2.5>100或连续1小时光照不足时发送通知"
CodeGenie生成响应:
class AlertService {
// 存储告警状态
private alertHistory: Map<string, number> = new Map();
checkEnvironment(alerts: EnvironmentAlert[]) {
alerts.forEach(alert => {
const key = `${alert.type}_${alert.location}`;
if (alert.shouldAlert()) {
// 首次触发或上次触发超过1小时
if (!this.alertHistory.has(key) ||
Date.now() - this.alertHistory.get(key)! > 3600000) {
this.sendNotification(alert.message);
this.alertHistory.set(key, Date.now());
}
} else {
// 恢复正常状态清除告警记录
if (this.alertHistory.has(key)) {
this.alertHistory.delete(key);
}
}
});
}
private sendNotification(message: string) {
Notification.requestEnable().then(() => {
Notification.publish({
content: {
contentType: Notification.ContentType.NOTIFICATION_TEXT,
normal: {
title: '环境异常告警',
text: message
}
}
});
// 手机震动提示
vibrator.vibrate(1000);
});
}
}
class EnvironmentAlert {
constructor(
public type: string,
public location: string,
public currentValue: number,
public threshold: number
) {}
shouldAlert(): boolean {
switch(this.type) {
case 'temperature': return this.currentValue > this.threshold;
case 'pm25': return this.currentValue > this.threshold;
case 'light': return this.currentValue < this.threshold;
}
return false;
}
get message(): string {
return `检测到${this.location}的${this.getTypeName()}异常:${this.currentValue}${this.getUnit()}(超过${this.threshold}${this.getUnit()})`;
}
private getTypeName(): string {
switch(this.type) {
case 'temperature': return '温度';
case 'pm25': return 'PM2.5';
case 'light': return '光照强度';
}
return '';
}
}
8. 设置页面和本地化存储
"创建设置页面:包含语言选择、温度单位切换、通知设置等,使用Preferences保存设置"
CodeGenie生成响应:
@Component
struct SettingsPage {
@State tempUnit: 'celsius' | 'fahrenheit' = 'celsius'
@State notificationEnabled: boolean = true
@State language: string = 'zh'
build() {
List() {
ListItem() {
Row() {
Text('温度单位').fontSize(18)
ToggleGroup({
options: [
{ label: '℃', value: 'celsius' },
{ label: '℉', value: 'fahrenheit' }
],
selected: this.tempUnit,
onChange: (unit) => this.changeTempUnit(unit)
})
}
}
ListItem() {
Row() {
Text('异常通知').fontSize(18).layoutWeight(1)
Toggle({ type: ToggleType.Switch, isOn: this.notificationEnabled })
.onChange(isOn => this.toggleNotifications(isOn))
}
}
ListItem() {
Row() {
Text('系统语言').fontSize(18)
Picker({
selected: this.language,
options: [
{ label: '中文', value: 'zh' },
{ label: 'English', value: 'en' }
],
onChange: (lang) => this.changeLanguage(lang)
}).margin(10)
}
}
}
}
aboutToAppear() {
this.loadSettings();
}
private async loadSettings() {
const prefs = Preferences.getPreferences('app_settings');
this.tempUnit = await prefs.get('tempUnit', 'celsius');
this.language = await prefs.get('language', 'zh');
this.notificationEnabled = await prefs.get('notifications', true);
}
private changeTempUnit(unit: any) {
this.tempUnit = unit;
Preferences.getPreferences('app_settings').put('tempUnit', unit);
}
private changeLanguage(lang: string) {
this.language = lang;
Preferences.getPreferences('app_settings').put('language', lang);
}
private toggleNotifications(enabled: boolean) {
this.notificationEnabled = enabled;
Preferences.getPreferences('app_settings').put('notifications', enabled);
}
}
CodeGenie开发成果统计
| 功能模块 | 人工开发时间 | CodeGenie开发时间 | 代码质量提升 |
|---|---|---|---|
| 应用框架与导航 | 2小时 | 15分钟 | ⭐⭐⭐⭐ |
| 数据采集与监控 | 3小时 | 25分钟 | ⭐⭐⭐⭐ |
| 健康分析算法 | 6小时 | 45分钟 | ⭐⭐⭐⭐⭐ |
| 设备控制面板 | 4小时 | 30分钟 | ⭐⭐⭐⭐ |
| 数据可视化 | 5小时 | 35分钟 | ⭐⭐⭐⭐⭐ |
| 告警系统 | 3小时 | 40分钟 | ⭐⭐⭐⭐ |
| 设置与本地存储 | 2小时 | 20分钟 | ⭐⭐⭐ |
| 总计 | 25小时 | 3.5小时 | 效率提升700% |
经验总结与最佳实践
CodeGenie使用技巧
- 迭代式开发:首先生成基础框架,再逐步添加功能细节
- 参数化提示:在提示中明确具体参数(如"PM2.5>100"而非"高污染")
- 组件复用:使用"参考现有组件X生成类似功能"提示复用设计
- 错误处理:添加"包含异常处理逻辑"到提示中提升代码健壮性
- 性能优化:使用"生成高性能实现"提示确保代码效率
通过这个完整实例,您可以看到:
- CodeGenie大幅减少重复性编码工作
- 复杂算法和数据结构可快速原型实现
- UI组件库集成变得简单高效
- 底层API使用不再需要查阅冗长文档
- 整个开发过程更加聚焦业务价值而非技术实现细节

被折叠的 条评论
为什么被折叠?



