鸿蒙宠物情绪识别应用开发指南 原创

进修的泡芙
发布于 2025-6-22 17:24
浏览
0收藏

鸿蒙宠物情绪识别应用开发指南

一、系统架构设计

基于HarmonyOS的AI能力和分布式技术,我们设计了一套宠物情绪识别系统,主要功能包括:
宠物面部识别:通过摄像头检测宠物面部特征

情绪分析:AI分析宠物表情判断情绪状态

健康建议:根据情绪状态提供养护建议

多设备同步:跨设备同步宠物健康数据

异常预警:情绪异常时及时提醒主人

!https://example.com/harmony-pet-emotion-arch.png

二、核心代码实现
宠物面部检测服务

// PetFaceDetectionService.ets
import camera from ‘@ohos.multimedia.camera’;
import image from ‘@ohos.multimedia.image’;
import petai from ‘@ohos.ai.pet’;

class PetFaceDetectionService {
private static instance: PetFaceDetectionService;
private cameraManager: camera.CameraManager;
private petDetector: petai.PetDetector;
private cameraInput: camera.CameraInput | null = null;
private previewOutput: camera.PreviewOutput | null = null;
private isDetecting: boolean = false;

private constructor() {
this.cameraManager = camera.getCameraManager();
this.petDetector = petai.createPetDetector();
public static getInstance(): PetFaceDetectionService {

if (!PetFaceDetectionService.instance) {
  PetFaceDetectionService.instance = new PetFaceDetectionService();

return PetFaceDetectionService.instance;

public async initCamera(previewSurfaceId: string): Promise<void> {

const cameras = this.cameraManager.getSupportedCameras();
if (cameras.length === 0) {
  throw new Error('No camera available');

this.cameraInput = this.cameraManager.createCameraInput(cameras[0]);

await this.cameraInput.open();

const previewProfile = this.cameraManager.getSupportedOutputCapability(
  cameras[0],
  camera.ProfileMode.PROFILE_MODE_DEFAULT
).previewProfiles[0];

this.previewOutput = this.cameraManager.createPreviewOutput(
  previewProfile,
  previewSurfaceId
);

public async detectPetFace(image: image.Image): Promise<PetFaceResult> {

const detectionOptions = {
  featureType: petai.FeatureType.FEATURE_TYPE_EMOTION,
  petType: petai.PetType.PET_TYPE_CAT_DOG
};

return new Promise((resolve, reject) => {
  this.petDetector.detect(image, detectionOptions, (err, result) => {
    if (err) {
      reject(err);

else {

      resolve(this.processPetFaceResult(result));

});

});

private processPetFaceResult(rawData: any): PetFaceResult {

if (!rawData || rawData.faces.length === 0) {
  return { faceDetected: false };

const face = rawData.faces[0];

return {
  faceDetected: true,
  boundingBox: face.boundingBox,
  landmarks: face.landmarks,
  petType: face.petType,
  emotion: face.emotion,
  confidence: face.confidence,
  timestamp: Date.now()
};

public startRealTimeDetection(callback: (result: PetFaceResult) => void): void {

this.isDetecting = true;

const interval = setInterval(async () => {
  if (!this.isDetecting) {
    clearInterval(interval);
    return;

try {

    const image = await this.captureFrame();
    const result = await this.detectPetFace(image);
    callback(result);

catch (error) {

    console.error('Detection error:', error);

}, 1000); // 每秒检测一次

public stopRealTimeDetection(): void {

this.isDetecting = false;

private async captureFrame(): Promise<image.Image> {

// 简化实现,实际应从预览流获取帧
return new Promise((resolve) => {
  const mockImage = {};
  resolve(mockImage as image.Image);
});

}

export const petDetectionService = PetFaceDetectionService.getInstance();

情绪分析服务

// PetEmotionAnalysisService.ets
import http from ‘@ohos.net.http’;

class PetEmotionAnalysisService {
private static instance: PetEmotionAnalysisService;
private httpClient: http.HttpRequest;
private apiKey = ‘YOUR_PET_EMOTION_API_KEY’;

private constructor() {
this.httpClient = http.createHttp();
public static getInstance(): PetEmotionAnalysisService {

if (!PetEmotionAnalysisService.instance) {
  PetEmotionAnalysisService.instance = new PetEmotionAnalysisService();

return PetEmotionAnalysisService.instance;

public async analyzeEmotion(faceData: PetFaceResult): Promise<EmotionAnalysis> {

return new Promise((resolve, reject) => {
  this.httpClient.request(
    'https://pet-emotion-api.example.com/analyze',

method: ‘POST’,

      header: { 'Content-Type': 'application/json' },
      extraData: JSON.stringify({
        landmarks: faceData.landmarks,
        pet_type: faceData.petType,
        api_key: this.apiKey
      })
    },
    (err, data) => {
      if (err) {
        reject(err);

else {

        const result = JSON.parse(data.result);
        resolve(this.processEmotionResult(result));

}

  );
});

private processEmotionResult(rawData: any): EmotionAnalysis {

return {
  emotion: rawData.emotion || 'neutral',
  confidence: rawData.confidence || 0,
  healthStatus: rawData.health_status || 'normal',
  suggestions: rawData.suggestions || [],
  timestamp: Date.now()
};

public getEmotionDescription(emotion: string, petType: string): string {

const descriptions: Record<string, Record<string, string>> = {
  happy: {
    cat: '猫咪看起来很开心,可能刚吃饱或正在玩耍',
    dog: '狗狗很兴奋,尾巴摇动,可能想和你玩'
  },
  angry: {
    cat: '猫咪可能感到威胁,耳朵向后,尾巴摆动',
 
  },
  scared: {
    cat: '猫咪感到害怕,身体蜷缩,耳朵贴平',
    dog: '狗狗显得害怕,尾巴夹起,可能需要安慰'
  },
  sick: {
    cat: '猫咪可能不舒服,精神萎靡,食欲不振',
    dog: '狗狗看起来不适,建议检查健康状况'
  },
  neutral: {
    cat: '猫咪状态正常,正在休息或观察周围',
    dog: '狗狗处于平静状态,一切正常'

};

return descriptions[emotion]?.[petType] || '情绪状态未知';

}

export const emotionAnalysisService = PetEmotionAnalysisService.getInstance();

多设备同步服务

// PetSyncService.ets
import distributedData from ‘@ohos.data.distributedData’;

class PetSyncService {
private static instance: PetSyncService;
private kvManager: distributedData.KVManager;
private kvStore: distributedData.KVStore;

private constructor() {
this.initKVStore();
private async initKVStore(): Promise<void> {

const config = {
  bundleName: 'com.example.petEmotion',
  userInfo: { userId: 'currentUser' }
};

this.kvManager = distributedData.createKVManager(config);
this.kvStore = await this.kvManager.getKVStore('pet_store', {
  createIfMissing: true
});

this.kvStore.on('dataChange', (data) => {
  this.handleRemoteUpdate(data);
});

public static getInstance(): PetSyncService {

if (!PetSyncService.instance) {
  PetSyncService.instance = new PetSyncService();

return PetSyncService.instance;

public async syncPetProfile(pet: PetProfile): Promise<void> {

await this.kvStore.put(pet_${pet.id}, JSON.stringify(pet));

public async getPetProfile(petId: string): Promise<PetProfile | null> {

const value = await this.kvStore.get(pet_${petId});
return value ? JSON.parse(value) : null;

public async syncEmotionRecord(record: EmotionRecord): Promise<void> {

await this.kvStore.put(emotion_${record.id}, JSON.stringify(record));

public async getEmotionRecords(petId: string): Promise<EmotionRecord[]> {

const entries = await this.kvStore.getEntries('emotion_');
return Array.from(entries)
  .map(([_, value]) => JSON.parse(value))
  .filter(record => record.petId === petId)
  .sort((a, b) => b.timestamp - a.timestamp);

public async syncHealthAlert(alert: HealthAlert): Promise<void> {

await this.kvStore.put(alert_${alert.id}, JSON.stringify(alert));

public async getHealthAlerts(petId: string): Promise<HealthAlert[]> {

const entries = await this.kvStore.getEntries('alert_');
return Array.from(entries)
  .map(([_, value]) => JSON.parse(value))
  .filter(alert => alert.petId === petId)
  .sort((a, b) => b.timestamp - a.timestamp);

private handleRemoteUpdate(data: distributedData.ChangeInfo): void {

if (data.deviceId === deviceInfo.deviceId) return;

const key = data.key as string;
if (key.startsWith('pet_')) {
  const pet = JSON.parse(data.value);
  EventBus.emit('petProfileUpdated', pet);

else if (key.startsWith(‘emotion_’)) {

  const record = JSON.parse(data.value);
  EventBus.emit('emotionRecordUpdated', record);

else if (key.startsWith(‘alert_’)) {

  const alert = JSON.parse(data.value);
  EventBus.emit('healthAlertUpdated', alert);

}

export const petSyncService = PetSyncService.getInstance();

三、主界面实现
实时检测界面

// PetCameraView.ets
@Component
struct PetCameraView {
@State previewSurfaceId: string = ‘’;
@State currentPet: PetProfile | null = null;
@State emotionResult: EmotionAnalysis | null = null;
@State isDetecting: boolean = false;
@State lastPhoto: image.Image | null = null;

aboutToAppear() {
this.loadCurrentPet();
this.initCamera();
build() {

Stack() {
  // 相机预览
  XComponent({
    id: 'petCameraPreview',
    type: 'surface',
    libraryname: 'libcamera.so',
    controller: this.previewController
  })
  .onLoad(() => {
    this.previewSurfaceId = this.previewController.getXComponentSurfaceId();
    petDetectionService.initCamera(this.previewSurfaceId);
  })
  .width('100%')
  .height('100%')
  
  // 宠物信息
  if (this.currentPet) {
    Column() {
      Row() {
        Image(this.currentPet.avatar)
          .width(40)
          .height(40)
          .borderRadius(20)
        
        Text(this.currentPet.name)
          .fontSize(18)
          .margin({ left: 8 })

.alignSelf(ItemAlign.Start)

      .margin({ top: 16, left: 16 })

}

  // 检测按钮
  Button(this.isDetecting ? '停止检测' : '开始检测情绪')
    .onClick(() => this.toggleDetection())
    .position({ x: '50%', y: '90%' })
  
  // 检测结果
  if (this.emotionResult) {
    EmotionResultView({ result: this.emotionResult, petType: this.currentPet?.type || 'cat' })
      .position({ x: '50%', y: '30%' })

// 拍照按钮

  if (this.isDetecting) {
    Button('拍照记录')
      .onClick(() => this.capturePhoto())
      .position({ x: '50%', y: '80%' })

}

private async loadCurrentPet(): Promise<void> {

this.currentPet = await petSyncService.getPetProfile('default_pet');

private async initCamera(): Promise<void> {

await petDetectionService.initCamera(this.previewSurfaceId);

private toggleDetection(): void {

if (this.isDetecting) {
  petDetectionService.stopRealTimeDetection();

else {

  petDetectionService.startRealTimeDetection(async (result) => {
    if (result.faceDetected) {
      this.emotionResult = await emotionAnalysisService.analyzeEmotion(result);
      
      // 异常情绪预警
      if (this.emotionResult.healthStatus === 'warning') {
        this.sendHealthAlert(result);

}

  });

this.isDetecting = !this.isDetecting;

private async capturePhoto(): Promise<void> {

if (!this.currentPet || !this.emotionResult) return;

this.lastPhoto = await petDetectionService.captureFrame();

const record: EmotionRecord = {
  id: generateId(),
  petId: this.currentPet.id,
  emotion: this.emotionResult.emotion,
  confidence: this.emotionResult.confidence,
  healthStatus: this.emotionResult.healthStatus,
  image: this.lastPhoto,
  timestamp: Date.now()
};

await petSyncService.syncEmotionRecord(record);
EventBus.emit('emotionRecorded', record);

private async sendHealthAlert(faceResult: PetFaceResult): Promise<void> {

if (!this.currentPet) return;

const alert: HealthAlert = {
  id: generateId(),
  petId: this.currentPet.id,
  type: 'emotion',
  level: 'warning',
  message: 宠物情绪异常: ${this.emotionResult?.emotion},
  timestamp: Date.now(),
  image: await petDetectionService.captureFrame()
};

await petSyncService.syncHealthAlert(alert);
EventBus.emit('healthAlert', alert);

}

@Component
struct EmotionResultView {
private result: EmotionAnalysis;
private petType: string;

build() {
Column() {
Text(this.getEmotionText())
.fontSize(20)
.fontColor(this.getEmotionColor())

  Text(置信度: ${Math.round(this.result.confidence * 100)}%)
    .fontSize(16)
    .margin({ top: 8 })
  
  if (this.result.healthStatus !== 'normal') {
    Text(this.getHealthStatusText())
      .fontSize(16)
      .fontColor('#FF5722')
      .margin({ top: 8 })

if (this.result.suggestions.length > 0) {

    Column() {
      Text('建议:')
        .fontSize(16)
        .margin({ top: 8 })
      
      ForEach(this.result.suggestions, (suggestion) => {
        Text(• ${suggestion})
          .fontSize(14)
          .margin({ top: 4 })
      })

.margin({ top: 8 })

}

.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(8)
.shadow({ radius: 4, color: '#00000020' })

private getEmotionText(): string {

const emotionMap: Record<string, string> = {
  happy: '开心',
  angry: '生气',
  scared: '害怕',
  sick: '不适',
  neutral: '平静'
};

return {emotionMap[this.result.emotion] || this.result.emotion} - {
  emotionAnalysisService.getEmotionDescription(this.result.emotion, this.petType)
};

private getEmotionColor(): string {

const colorMap: Record<string, string> = {
  happy: '#4CAF50',
  angry: '#F44336',
  scared: '#FF9800',
  sick: '#9C27B0',
  neutral: '#2196F3'
};

return colorMap[this.result.emotion] || '#000000';

private getHealthStatusText(): string {

return this.result.healthStatus === 'warning' ? 
  '健康预警! 请关注宠物状态' : '宠物状态正常';

}

function generateId(): string {
return Math.random().toString(36).substring(2) + Date.now().toString(36);

情绪历史界面

// EmotionHistoryView.ets
@Component
struct EmotionHistoryView {
@State records: EmotionRecord[] = [];
@State currentPet: PetProfile | null = null;
@State selectedDate: string = new Date().toISOString().split(‘T’)[0];

aboutToAppear() {
this.loadCurrentPet();
this.loadRecords();
EventBus.on(‘emotionRecordUpdated’, () => this.loadRecords());
build() {

Column() {
  if (this.currentPet) {
    Row() {
      Image(this.currentPet.avatar)
        .width(40)
        .height(40)
        .borderRadius(20)
      
      Text(this.currentPet.name)
        .fontSize(18)
        .margin({ left: 8 })

.margin({ top: 16 })

    // 日期选择
    DatePicker({
      start: '2020-01-01',
      end: '2030-12-31',
      selected: this.selectedDate
    })
    .onChange((date: string) => {
      this.selectedDate = date;
      this.loadRecords();
    })
    .margin({ top: 16 })
    
    // 情绪统计
    if (this.records.length > 0) {
      Row() {
        ForEach(this.getEmotionStats(), (stat) => {
          Column() {
            Text(stat.emotion)
              .fontSize(14)
            
            Text(stat.count.toString())
              .fontSize(18)
              .fontColor(this.getEmotionColor(stat.emotion))
              .margin({ top: 4 })

.margin(8)

        })

.margin({ top: 16 })

// 记录列表

    if (this.records.length === 0) {
      Text('暂无情绪记录')
        .fontSize(16)
        .margin({ top: 32 })

else {

      List({ space: 10 }) {
        ForEach(this.records, (record) => {
          ListItem() {
            EmotionRecordItem({ record })

})

.layoutWeight(1)

} else {

    Text('请先添加宠物')
      .fontSize(16)
      .margin({ top: 32 })

}

.padding(16)

private async loadCurrentPet(): Promise<void> {

this.currentPet = await petSyncService.getPetProfile('default_pet');

private async loadRecords(): Promise<void> {

if (!this.currentPet) return;

const allRecords = await petSyncService.getEmotionRecords(this.currentPet.id);
this.records = allRecords.filter(record => 
  new Date(record.timestamp).toISOString().split('T')[0] === this.selectedDate
);

private getEmotionStats(): { emotion: string; count: number }[] {

const stats: Record<string, number> = {};

this.records.forEach(record => {
  stats[record.emotion] = (stats[record.emotion] || 0) + 1;
});

return Object.entries(stats).map(([emotion, count]) => ({
  emotion,
  count
}));

private getEmotionColor(emotion: string): string {

const colorMap: Record<string, string> = {
  happy: '#4CAF50',
  angry: '#F44336',
  scared: '#FF9800',
  sick: '#9C27B0',
  neutral: '#2196F3'
};

return colorMap[emotion] || '#000000';

}

@Component
struct EmotionRecordItem {
private record: EmotionRecord;

build() {
Row() {
Column() {
Text(this.getEmotionText())
.fontSize(16)
.fontColor(this.getEmotionColor())

    Text(formatTime(this.record.timestamp))
      .fontSize(14)
      .fontColor('#666666')
      .margin({ top: 4 })

.layoutWeight(1)

  if (this.record.healthStatus !== 'normal') {
    Text('⚠️')
      .fontSize(20)

}

.padding(12)
.onClick(() => {
  EventBus.emit('showEmotionDetail', this.record);
})

private getEmotionText(): string {

const emotionMap: Record<string, string> = {
  happy: '开心',
  angry: '生气',
  scared: '害怕',
  sick: '不适',
  neutral: '平静'
};

return {emotionMap[this.record.emotion] || this.record.emotion} ({Math.round(this.record.confidence * 100)}%);

private getEmotionColor(): string {

const colorMap: Record<string, string> = {
  happy: '#4CAF50',
  angry: '#F44336',
  scared: '#FF9800',
  sick: '#9C27B0',
  neutral: '#2196F3'
};

return colorMap[this.record.emotion] || '#000000';

}

function formatTime(timestamp: number): string {
const date = new Date(timestamp);
return {date.getHours()}:{date.getMinutes().toString().padStart(2, ‘0’)};

健康预警界面

// HealthAlertView.ets
@Component
struct HealthAlertView {
@State alerts: HealthAlert[] = [];
@State currentPet: PetProfile | null = null;

aboutToAppear() {
this.loadCurrentPet();
this.loadAlerts();
EventBus.on(‘healthAlertUpdated’, () => this.loadAlerts());
build() {

Column() {
  if (this.currentPet) {
    Text(健康预警 - ${this.currentPet.name})
      .fontSize(20)
      .fontWeight(FontWeight.Bold)
      .margin({ top: 16 })
    
    if (this.alerts.length === 0) {
      Text('暂无健康预警')
        .fontSize(16)
        .margin({ top: 32 })

else {

      List({ space: 10 }) {
        ForEach(this.alerts, (alert) => {
          ListItem() {
            HealthAlertItem({ alert })

})

.layoutWeight(1)

} else {

    Text('请先添加宠物')
      .fontSize(16)
      .margin({ top: 32 })

}

.padding(16)

private async loadCurrentPet(): Promise<void> {

this.currentPet = await petSyncService.getPetProfile('default_pet');

private async loadAlerts(): Promise<void> {

if (!this.currentPet) return;

this.alerts = await petSyncService.getHealthAlerts(this.currentPet.id);

}

@Component
struct HealthAlertItem {
private alert: HealthAlert;

build() {
Column() {
Row() {
Text(this.alert.message)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.layoutWeight(1)

    Text(formatDate(this.alert.timestamp))
      .fontSize(14)
      .fontColor('#666666')

if (this.alert.image) {

    Image(this.alert.image)
      .width('100%')
      .height(200)
      .margin({ top: 8 })
      .objectFit(ImageFit.Contain)

Divider()

    .margin({ top: 8 })

.padding(12)

}

function formatDate(timestamp: number): string {
const date = new Date(timestamp);
return {date.getFullYear()}-{date.getMonth() + 1}-{date.getDate()} {date.getHours()}:${date.getMinutes()};

四、高级功能实现
多设备健康预警

// CollaborativeAlertService.ets
class CollaborativeAlertService {
private static instance: CollaborativeAlertService;

private constructor() {}

public static getInstance(): CollaborativeAlertService {
if (!CollaborativeAlertService.instance) {
CollaborativeAlertService.instance = new CollaborativeAlertService();
return CollaborativeAlertService.instance;

public async broadcastAlert(alert: HealthAlert): Promise<void> {

const devices = await deviceManager.getTrustedDevices();
await Promise.all(devices.map(device => 
  this.sendAlertToDevice(device.id, alert)
));

private async sendAlertToDevice(deviceId: string, alert: HealthAlert): Promise<void> {

const ability = await featureAbility.startAbility({
  bundleName: 'com.example.petEmotion',
  abilityName: 'HealthAlertAbility',
  deviceId
});

await ability.call({
  method: 'receiveHealthAlert',
  parameters: [alert]
});

public async syncAllAlertsToNewDevice(deviceId: string): Promise<void> {

const alerts = await petSyncService.getHealthAlerts('default_pet');
const ability = await featureAbility.startAbility({
  bundleName: 'com.example.petEmotion',
  abilityName: 'AlertSyncAbility',
  deviceId
});

await ability.call({
  method: 'receiveMultipleAlerts',
  parameters: [alerts]
});

}

export const alertService = CollaborativeAlertService.getInstance();

宠物健康分析

// PetHealthAnalysisService.ets
class PetHealthAnalysisService {
private static instance: PetHealthAnalysisService;

private constructor() {}

public static getInstance(): PetHealthAnalysisService {
if (!PetHealthAnalysisService.instance) {
PetHealthAnalysisService.instance = new PetHealthAnalysisService();
return PetHealthAnalysisService.instance;

public analyzeEmotionTrend(records: EmotionRecord[]): HealthReport {

const report: HealthReport = {
  overallStatus: 'normal',
  emotionDistribution: this.getEmotionDistribution(records),
  warningSigns: [],
  suggestions: []
};

// 分析情绪趋势
const last7Days = records.filter(r => 
  Date.now() - r.timestamp < 7  24  60  60  1000
);

const negativeCount = last7Days.filter(r => 
  ['angry', 'scared', 'sick'].includes(r.emotion)
).length;

if (negativeCount > 5) {
  report.overallStatus = 'warning';
  report.warningSigns.push('近期负面情绪较多');
  report.suggestions.push('建议检查宠物生活环境或咨询兽医');

// 检查是否有连续不适记录

const sickRecords = records.filter(r => r.emotion === 'sick');
if (sickRecords.length >= 3) {
  report.overallStatus = 'critical';
  report.warningSigns.push('多次检测到不适情绪');
  report.suggestions.push('建议立即带宠物就医检查');

return report;

private getEmotionDistribution(records: EmotionRecord[]): EmotionDistribution {

const distribution: EmotionDistribution = {
  happy: 0,
  angry: 0,
  scared: 0,
  sick: 0,
  neutral: 0
};

records.forEach(record => {
  distribution[record.emotion]++;
});

return distribution;

public generateWeeklyReport(petId: string, records: EmotionRecord[]): WeeklyReport {

const report: WeeklyReport = {
  petId,
  weekStart: this.getWeekStartDate(),
  emotionStats: this.getEmotionStatsByDay(records),
  healthStatus: this.analyzeEmotionTrend(records).overallStatus,
  recommendations: []
};

// 根据情绪分布给出建议
if (report.emotionStats.happy < 3) {
  report.recommendations.push('增加与宠物的互动时间');

if (report.emotionStats.angry > 2) {

  report.recommendations.push('检查是否有让宠物感到压力的因素');

if (report.emotionStats.sick > 0) {

  report.recommendations.push('观察宠物食欲和精神状态');

return report;

private getWeekStartDate(): string {

const date = new Date();
const day = date.getDay();
const diff = date.getDate() - day + (day === 0 ? -6 : 1);
return new Date(date.setDate(diff)).toISOString().split('T')[0];

private getEmotionStatsByDay(records: EmotionRecord[]): EmotionStatsByDay {

const stats: EmotionStatsByDay = {};

records.forEach(record => {
  const date = new Date(record.timestamp).toISOString().split('T')[0];
  if (!stats[date]) {
    stats[date] = {
      happy: 0,
      angry: 0,
      scared: 0,
      sick: 0,
      neutral: 0
    };

stats[date][record.emotion]++;

});

return stats;

}

export const healthAnalysisService = PetHealthAnalysisService.getInstance();

智能提醒服务

// PetReminderService.ets
import reminderAgent from ‘@ohos.reminderAgent’;

class PetReminderService {
private static instance: PetReminderService;

private constructor() {}

public static getInstance(): PetReminderService {
if (!PetReminderService.instance) {
PetReminderService.instance = new PetReminderService();
return PetReminderService.instance;

public async scheduleDailyCheckup(pet: PetProfile): Promise<void> {

const reminderTime = this.getOptimalCheckupTime(pet);

const reminderRequest: reminderAgent.ReminderRequest = {
  reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER,
  actionButton: [{ title: '已完成' }, { title: '稍后提醒' }],
  wantAgent: {
    pkgName: 'com.example.petEmotion',
    abilityName: 'PetCheckupAbility'
  },
  ringDuration: 60,
  snoozeTimes: 2,
  triggerTime: reminderTime.getTime(),
  repeatInterval: 24  60  60 * 1000, // 每天重复
  title: 宠物健康检查 - ${pet.name},
  content: '记得检查宠物的情绪和健康状况',
  expiredContent: "检查提醒已过期"
};

await reminderAgent.publishReminder(reminderRequest);

private getOptimalCheckupTime(pet: PetProfile): Date {

// 根据宠物类型和习惯返回最佳检查时间
const time = new Date();

if (pet.type === 'cat') {
  time.setHours(10, 0, 0, 0); // 上午10点

else if (pet.type === ‘dog’) {

  time.setHours(18, 0, 0, 0); // 下午6点

else {

  time.setHours(12, 0, 0, 0); // 中午12点

return time;

public async scheduleVaccineReminder(pet: PetProfile, vaccine: Vaccine): Promise<void> {

const reminderRequest: reminderAgent.ReminderRequest = {
  reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER,
  actionButton: [{ title: '已预约' }],
  wantAgent: {
    pkgName: 'com.example.petEmotion',
    abilityName: 'VaccineReminderAbility'
  },
  triggerTime: vaccine.date.getTime() - 3  24  60  60  1000, // 提前3天提醒
  title: 宠物疫苗提醒 - ${pet.name},
  content: ${vaccine.name}疫苗将在3天后到期,
  expiredContent: "疫苗提醒已过期"
};

await reminderAgent.publishReminder(reminderRequest);

public async cancelAllReminders(): Promise<void> {

const reminders = await reminderAgent.getValidReminders();
await Promise.all(reminders.map(rem => 
  reminderAgent.cancelReminder(rem.id)
));

}

export const reminderService = PetReminderService.getInstance();

五、总结

本宠物情绪识别应用实现了以下核心价值:
精准识别:AI技术准确识别宠物面部表情和情绪

健康监测:长期跟踪宠物情绪变化,预警健康问题

智能建议:根据情绪状态提供科学养护建议

多设备协同:家庭成员共享宠物健康数据

及时预警:异常情绪状态即时提醒主人

扩展方向:
增加宠物行为分析功能

集成宠物健康档案管理

开发宠物社交分享功能

对接宠物医疗服务机构

注意事项:
需要申请ohos.permission.CAMERA权限

识别准确率受光线和宠物姿势影响

健康预警仅供参考,不能替代专业兽医诊断

多设备协同需保持网络连接

首次使用建议完成宠物信息设置

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
已于2025-6-22 17:28:11修改
收藏
回复
举报
回复
    相关推荐