鸿蒙分布式智能门禁通知系统:多设备协同的人体检测与实时提醒方案 原创

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

鸿蒙分布式智能门禁通知系统:多设备协同的人体检测与实时提醒方案

一、系统架构设计

!https://example.com/harmonyos-doorbell-arch.png

采用四层架构:
感知层:门禁摄像头与传感器网络

分析层:分布式人体检测与身份识别

路由层:智能通知分发策略

展示层:多终端统一通知界面

二、核心模块实现
人体检测模块

// MotionDetector.ts
import image from ‘@ohos.multimedia.image’;
import bodyDetection from ‘@ohos.ai.bodyDetection’;
import distributedData from ‘@ohos.data.distributedData’;

interface DetectionResult {
timestamp: number;
deviceId: string;
personCount: number;
confidence: number;
image?: string; // Base64缩略图
export class MotionDetector {

private detector: bodyDetection.BodyDetector;
private kvManager: distributedData.KVManager;
private kvStore?: distributedData.KVStore;

async init() {
// 初始化人体检测器
this.detector = await bodyDetection.createDetector({
model: ‘fast’,
device: ‘NPU’
});

// 初始化分布式数据同步
const context = getContext(this);
this.kvManager = distributedData.createKVManager({ context });
this.kvStore = await this.kvManager.getKVStore('motion_detections', {
  createIfMissing: true,
  autoSync: true
});

async processFrame(image: image.Image): Promise<void> {

const result = await this.detector.detect(image);
if (result.personCount > 0) {
  const detection: DetectionResult = {
    timestamp: Date.now(),
    deviceId: 'door_camera',
    personCount: result.personCount,
    confidence: result.confidence,
    image: await this.compressImage(image)
  };
  
  await this.kvStore?.put(detection_${detection.timestamp}, detection);
  this.triggerNotification(detection);

}

private async compressImage(img: image.Image): Promise<string> {
// 实现图像压缩为Base64
return ‘data:image/jpeg;base64,…’;
// 其他方法…

智能通知路由

// NotificationRouter.ts
import deviceManager from ‘@ohos.distributedHardware.deviceManager’;
import notification from ‘@ohos.notification’;

export class NotificationRouter {
private deviceList: deviceManager.DeviceBasicInfo[] = [];

async init() {
const manager = await deviceManager.createDeviceManager(‘com.example.doorbell’);
manager.on(‘deviceStateChange’, () => this.refreshDeviceList());
await this.refreshDeviceList();
async triggerNotification(detection: DetectionResult) {

const targets = this.selectTargetDevices();
await Promise.all(targets.map(device => 
  this.sendToDevice(device.deviceId, detection)
));

private selectTargetDevices(): deviceManager.DeviceBasicInfo[] {

// 根据时间、位置等策略选择目标设备
const now = new Date();
const hour = now.getHours();

// 示例:晚上只通知手机设备
if (hour > 22 || hour < 6) {
  return this.deviceList.filter(d => d.deviceType === 'phone');

return this.deviceList; // 默认通知所有设备

private async sendToDevice(deviceId: string, detection: DetectionResult) {

try {
  await notification.publish({
    id: 1,
    deviceId,
    content: {
      title: '门口有人',
      text: 检测到${detection.personCount}人,
      additionalData: {
        image: detection.image,
        timestamp: detection.timestamp

}

  });

catch (err) {

  console.error(发送通知到${deviceId}失败:, err);

}

// 其他方法…

主页面实现(ArkUI)

// DoorbellApp.ets
import { MotionDetector } from ‘./MotionDetector’;
import { NotificationRouter } from ‘./NotificationRouter’;

@Entry
@Component
struct DoorbellApp {
@State detections: DetectionResult[] = [];
@State connectedDevices: number = 0;

private detector = new MotionDetector();
private notifier = new NotificationRouter();
private cameraController?: CameraController;

async aboutToAppear() {
await this.detector.init();
await this.notifier.init();
this.setupDetectionListener();
private setupDetectionListener() {

this.detector.on('detection', (result: DetectionResult) => {
  this.detections = [result, ...this.detections.slice(0, 9)]; // 保留最近10条
});

async startMonitoring() {

this.cameraController = new CameraController({
  onFrame: (image: image.Image) => this.detector.processFrame(image),
  frameRate: 1 // 每秒1帧足够用于门禁检测
});
this.cameraController.start();

build() {

Column() {
  // 设备连接状态
  Text(已连接设备: ${this.connectedDevices})
    .fontSize(16)
  
  // 最近检测记录
  List() {
    ForEach(this.detections, (detection) => {
      ListItem() {
        DetectionItem({ detection })

})

.height(‘60%’)

  // 控制按钮
  Button(this.cameraController?.isRunning ? '停止监控' : '开始监控')
    .onClick(() => 
      this.cameraController?.isRunning ? 
      this.cameraController.stop() : 
      this.startMonitoring()
    )

}

@Component

struct DetectionItem {
@Prop detection: DetectionResult;

build() {
Row() {
if (this.detection.image) {
Image(this.detection.image)
.width(80)
.height(60)
Column() {

    Text(时间: ${new Date(this.detection.timestamp).toLocaleTimeString()})
    Text(人数: ${this.detection.personCount})
    Text(置信度: ${(this.detection.confidence * 100).toFixed(1)}%)

.margin(10)

.padding(5)

.border({ width: 1, color: '#EEEEEE' })

}

三、跨设备协同关键实现
多视角人体追踪

// 在MotionDetector中添加
async trackAcrossDevices(detection: DetectionResult) {
const devices = await this.getAvailableCameras();
const results = await Promise.all(
devices.map(device =>
this.requestDetectionFromDevice(device.deviceId, detection.timestamp)
)
);

return this.mergeDetections(results.filter(r => r) as DetectionResult[]);
private async requestDetectionFromDevice(deviceId: string, timestamp: number) {

try {
const remoteStore = await distributedData.getRemoteKVStore(deviceId, ‘motion_detections’);
return await remoteStore.get(detection_${timestamp}) as DetectionResult;
catch (err) {

console.error(从${deviceId}获取检测结果失败:, err);
return null;

}

身份识别协同

// 新增FaceRecognizer.ts
export class FaceRecognizer {
private recognizer?: faceRecognition.FaceRecognizer;

async init() {
this.recognizer = await faceRecognition.createRecognizer({
model: ‘mobile_face’,
features: [‘age’, ‘gender’, ‘mask’]
});
async recognizeFromDetection(detection: DetectionResult): Promise<PersonInfo | null> {

if (!detection.image) return null;

const image = await this.loadImage(detection.image);
const result = await this.recognizer?.recognize(image);

return result ? {
  ageRange: {result.age - 5}-{result.age + 5},
  gender: result.gender,
  hasMask: result.attributes.includes('mask'),
  confidence: result.confidence

// 其他方法…

紧急情况协同处理

// 新增EmergencyHandler.ts
export class EmergencyHandler {
static async triggerEmergency(detection: DetectionResult) {
// 通知所有设备
await NotificationRouter.broadcastEmergency(detection);

// 触发安防设备
await this.activateSecurityDevices();

// 可选:联系预设紧急联系人
if (this.shouldCallEmergencyContact(detection)) {
  await this.dialEmergencyNumber();

}

// 其他方法…

四、性能优化方案
动态检测灵敏度

// 在MotionDetector中添加
private adjustSensitivity(): number {
const hour = new Date().getHours();
// 夜晚提高检测灵敏度
return hour > 22 || hour < 6 ? 0.7 : 0.9;
async processFrame(image: image.Image) {

const sensitivity = this.adjustSensitivity();
const result = await this.detector.detect(image, { minConfidence: sensitivity });
// …其余处理逻辑

分级通知策略

// 在NotificationRouter中添加
private getNotificationLevel(detection: DetectionResult): ‘normal’ ‘important’
‘emergency’ {
if (detection.personCount > 3) return ‘emergency’;
if (new Date().getHours() > 22) return ‘important’;
return ‘normal’;
async triggerNotification(detection: DetectionResult) {

const level = this.getNotificationLevel(detection);
const targets = this.selectTargetDevices(level);
// …发送通知

图像传输优化

// 在MotionDetector中添加
private async optimizeImageForTransmission(img: image.Image): Promise<string> {
// 降低分辨率并增加压缩比
const small = img.resize(320, 240);
return small.compress(0.7); // 70%质量

五、应用场景扩展
访客识别系统

class VisitorRecognizer {
async matchWithContacts(detection: DetectionResult) {
// 与通讯录照片比对识别访客
}

快递包裹检测

class PackageDetector {
async detectPackage(detection: DetectionResult) {
// 检测门口遗留包裹
}

宠物出入监控

class PetMonitor {
async trackPetMovement(detection: DetectionResult) {
// 识别宠物进出
}

智能场景联动

class SceneLinkage {
async activateWelcomeScene() {
// 有人到家时自动开灯等
}

本系统充分利用HarmonyOS分布式能力,实现了:
多设备协同检测:降低误报率,提高检测精度

智能通知路由:根据场景选择最优通知方式

紧急情况协同:多设备联动保障家庭安全

能效优化:动态调整检测策略降低功耗

开发者可以基于此框架扩展更多智能家居场景:
结合人脸识别的个性化迎宾

与智能门锁的联动控制

异常行为分析与预警

社区安全网络协同

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
收藏
回复
举报
回复
    相关推荐