CCTV Integration

🇹🇭 ภาษาไทย

CCTV Integration คือการนำข้อมูลจากระบบกล้องวงจรปิด (NVR/IP Camera) มาเชื่อมต่อกับระบบซอฟต์แวร์อื่นๆ — ไม่ใช่แค่ดู footage แบบ passive แต่ extract ข้อมูลออกมาใช้งาน เช่น ลงเวลาพนักงาน, บันทึกเข้า-ออกรถ, สำรองวิดีโออัตโนมัติ

ใน wiki นี้ใช้ Dahua.Api เป็น SDK หลักสำหรับอุปกรณ์ Dahua

3 Use Cases หลัก

CCTV System
    │
    ├── 1. Video Backup      → เก็บ footage สำรองอัตโนมัติ
    ├── 2. Face Recognition  → ลงเวลา / Access Control
    └── 3. LPR              → บันทึกเข้า-ออกรถยนต์

Use Case 1: Video Backup (สำรองวิดีโอ)

ปัญหาที่แก้

  • NVR เก็บวิดีโอใน HDD ของตัวเอง — เมื่อเต็มจะ overwrite ทับโดยอัตโนมัติ
  • ถ้าไม่ backup ออกมา footage เก่าจะหายหมด
  • Manual download ใช้เวลามากและ error-prone

Architecture

NVR (Dahua)
    │
    │  Dahua NetSDK / Dahua.Api
    ▼
Backup Service (.NET)
    │  ทำงานทุกคืน (Scheduled Job)
    │
    ├── FindFiles() → รายการวิดีโอเมื่อวาน
    ├── StartDownloadFile() → download ทีละไฟล์
    └── Progress tracking → log completion
    │
    ▼
Storage
    ├── Local NAS / External HDD
    ├── Network Share (SMB)
    └── Cloud Storage (Azure Blob, S3) ← convert แล้ว upload

Workflow

1. Scheduler trigger (ทุกคืน 02:00)
2. Init SDK + Login ทุก NVR
3. วน loop ทุก channel
4. FindFiles(เมื่อวาน 00:00 → 23:59)
5. ตรวจสอบว่าไฟล์นั้น backup แล้วหรือยัง (check DB/log)
6. ถ้ายัง → StartDownloadFile()
7. Monitor progress จนครบ 100%
8. บันทึกลง backup log database
9. Logout + Cleanup

ตัวแปรที่ต้องออกแบบ

ตัวแปรทางเลือก
Retention policyเก็บกี่วัน? กี่เดือน? ต่าง tier กัน
Naming convention{site}_{channel}_{date}_{time}.mp4
Storage tierHot (SSD/NAS) → Warm (HDD) → Cold (Cloud archive)
Dedup / hash checkMD5/SHA256 ป้องกัน duplicate download
Failure handlingRetry 3 ครั้ง → alert → mark failed

Use Case 2: Face Recognition — ลงเวลาพนักงาน

ปัญหาที่แก้

  • การลงเวลาแบบบัตร/นิ้วโป้ง มีความเสี่ยงโกง (buddy punching)
  • ต้องการระบบที่ไม่ต้อง physical touch
  • เชื่อมกับระบบ HR/payroll โดยอัตโนมัติ

Architecture

กล้อง Dahua (Face Detection)
    │
    │  Face Detection Event Stream
    ▼
Event Handler (.NET Service)
    │
    ├── Person ID + Confidence + Timestamp + Channel
    │
    ▼
Business Logic Layer
    │
    ├── Lookup: Person ID → Employee ID (Face Library DB)
    ├── Validate: confidence > threshold (เช่น 0.85)
    ├── Determine: เข้างาน / ออกงาน (by schedule / last state)
    └── Record: Insert attendance record
    │
    ▼
Attendance Database
    └── ส่งต่อไปยัง HR System / Payroll

Face Library Management

Operationวิธี
เพิ่มใบหน้าใหม่Dahua HTTP API (POST face image + person metadata)
อัพเดทรูปPUT request พร้อม person ID
ลบออกDELETE person ID จาก face library
SyncPull face library list ทุกคืน เพื่อ verify consistency

Event Data ที่ได้รับ

{
  "PersonID": "EMP001",
  "Confidence": 0.92,
  "Timestamp": "2026-04-20T08:03:41",
  "Channel": 3,
  "ImageSnapshot": "base64...",
  "Direction": "Enter"
}

Rules สำหรับ Attendance Logic

กรณีAction
ครั้งแรกของวันบันทึกเป็น “เข้างาน”
ครั้งถัดไป (> 4 ชั่วโมงหลังเข้า)บันทึกเป็น “ออกงาน”
Confidence < thresholdignore หรือ flag for review
นอกเวลาทำงานบันทึก แต่ flag เป็น overtime/unauthorized
กล้องหลายตัว (multi-camera)dedup ใน 30 วินาที (anti-ghost)

⚠️ สำคัญมาก — การเก็บข้อมูลใบหน้าในไทยอยู่ภายใต้ พ.ร.บ. คุ้มครองข้อมูลส่วนบุคคล (PDPA)

  • ต้องขอความยินยอม (consent) จากพนักงาน
  • ต้องแจ้งวัตถุประสงค์การใช้ข้อมูลชัดเจน
  • ต้องกำหนด retention period และ data deletion policy
  • ห้าม share biometric data กับ third party โดยไม่ได้รับอนุญาต

Use Case 3: LPR — บันทึกเข้า-ออกรถยนต์

ปัญหาที่แก้

  • บันทึกรถเข้า-ออกอาคาร/ที่จอดรถแบบอัตโนมัติ
  • ควบคุม access (เปิดไม้กั้นอัตโนมัติสำหรับรถที่อนุญาต)
  • สืบค้นย้อนหลังได้ว่ารถคันไหนเข้ามาเมื่อไหร่

Architecture

กล้อง LPR (Dahua)
    │
    │  LPR Event (Plate + Direction + Image)
    ▼
LPR Event Handler
    │
    ├── Extract: plate number + timestamp + direction
    ├── Normalize: ตัวพิมพ์ใหญ่, ลบ space
    ├── Lookup: plate ∈ whitelist?
    │
    ├── [Yes] → Trigger Gate Open + Log "Authorized Entry"
    └── [No]  → Log "Unauthorized" + Optional Alert
    │
    ▼
Vehicle Log Database
    ├── vehicle_log: plate, timestamp, direction, authorized
    └── dwell_time: entry_time, exit_time, duration

Event Data จาก LPR

{
  "PlateNumber": "กข1234",
  "Province": "กรุงเทพมหานคร",
  "Confidence": 0.95,
  "Timestamp": "2026-04-20T09:15:22",
  "Direction": "Enter",
  "Channel": 1,
  "PlateImage": "base64...",
  "VehicleImage": "base64..."
}

Gate Control Integration

LPR Match → HTTP POST → Gate Controller (Wiegand / RS485 / IP Relay)
                             │
                             └── Trigger Relay → เปิดไม้กั้น (500ms)

Reports ที่ระบบควร Generate

Reportเนื้อหา
Daily Entry/Exitรายการรถทุกคันแยกวัน
Dwell Timeรถอยู่นานแค่ไหน (สำหรับบริหารที่จอดรถ)
Unauthorized Attemptsรถที่ไม่ได้รับอนุญาตพยายามเข้า
Monthly Summaryสถิติรวม, peak hours

System Architecture รวม (ทั้ง 3 Use Cases)

┌─────────────────────────────────────────────────────┐
│                  NVR / IP Camera Layer               │
│   [Dahua NVR] ←→ [IP Cam 1] [IP Cam 2] [LPR Cam]   │
└────────────────────────┬────────────────────────────┘
                         │ Dahua NetSDK / HTTP API
                         ▼
┌─────────────────────────────────────────────────────┐
│              Integration Service (.NET)              │
│                                                      │
│  ┌──────────────┐  ┌─────────────┐  ┌────────────┐  │
│  │ Video Backup │  │ Face Recog. │  │    LPR     │  │
│  │   Worker     │  │   Service   │  │  Service   │  │
│  └──────┬───────┘  └──────┬──────┘  └─────┬──────┘  │
└─────────┼────────────────┼───────────────┼──────────┘
          ▼                ▼               ▼
┌─────────────────────────────────────────────────────┐
│                   Data Layer                         │
│                                                      │
│  [Backup Storage]  [Attendance DB]  [Vehicle Log DB] │
│       │                  │                │          │
│       │            [HR/Payroll]     [Gate Controller]│
│       │                  │                           │
│       └──────────[Reporting Dashboard]───────────────│
└─────────────────────────────────────────────────────┘

Tech Stack แนะนำ

LayerTechnology
SDKDahua.Api (.NET) + Dahua HTTP API
SchedulerHangfire / Quartz.NET / Windows Task Scheduler
DatabaseSQL Server / PostgreSQL
Message QueueRabbitMQ / Azure Service Bus (สำหรับ event stream)
StorageLocal NAS + Azure Blob / S3 (cold archive)
DashboardGrafana / custom web app
Gate ControlHTTP API to IP Relay Controller

เปรียบเทียบ Vendor SDK

VendorSDKProtocolPlatform
DahuaDahua.Api / NetSDKProprietarywin-x64
HikvisionHikVisionNet.OpenSDKProprietarywin-x64
AxisVAPIX APIHTTP RESTCross-platform
GenericONVIFSOAP/WSCross-platform

ถ้าต้องการ cross-vendor ให้ใช้ ONVIF เป็น common interface แต่ฟีเจอร์ขั้นสูง (face recognition, LPR) ยังต้องใช้ proprietary SDK ของแต่ละ vendor

  • Dahua.Api — C# SDK สำหรับอุปกรณ์ Dahua
  • BLEAF — enterprise workflow ที่อาจรับข้อมูลลงเวลาจาก Face Recognition

🇬🇧 English

CCTV Integration refers to connecting camera systems (NVR/IP cameras) to software workflows — extracting structured data rather than passively recording footage. Core use cases: automated video backup, face recognition for attendance, and license plate recognition for vehicle access control.

In this wiki, Dahua.Api is the primary SDK for Dahua hardware.

Three Core Use Cases

1. Video Backup — Automated Footage Archival

Problem: NVRs overwrite HDD storage on a rolling basis; without active extraction, historical footage is permanently lost.

Solution Pattern:

  • Nightly scheduled job per NVR/channel
  • VideoService.FindFiles(yesterday) → enumerate recordings
  • Check backup log DB to skip already-downloaded files
  • StartDownloadFile() + progress tracking loop
  • Write completion record to DB

Design Decisions:

  • Retention tiers: hot (SSD/NAS, 30 days) → warm (HDD, 6 months) → cold (cloud archive, 7 years)
  • File naming: {site}_{channel}_{YYYYMMDD_HHmmss}_{duration}.mp4
  • Deduplication: SHA256 hash check before download
  • Error handling: retry 3×, alert on persistent failure, mark as failed in log

2. Face Recognition → Employee Attendance

Problem: Card/fingerprint systems are susceptible to buddy punching; physical contact required.

Architecture:

  1. Dahua NVR emits face detection events (person ID, confidence, timestamp, channel, snapshot)
  2. Event handler filters by confidence threshold (e.g. ≥ 0.85)
  3. Business logic maps person ID → employee record
  4. Determines in/out based on last recorded state and schedule
  5. Inserts attendance record → HR/payroll system

Face Library Sync: Add/update/remove employee face images via Dahua HTTP API (port 80). Nightly consistency check between face library and HR employee list.

Anti-ghost rule: De-duplicate events from multiple cameras within a 30-second window to prevent duplicate attendance records.

PDPA Compliance (Thailand):

  • Written consent required from all employees
  • Purpose limitation: attendance only, no sharing with third parties
  • Defined retention period with secure deletion
  • Data subject rights: access, correction, deletion on request

3. LPR — Vehicle Entry/Exit Logging

Problem: Manual vehicle logging is slow, error-prone, and unauditable.

Architecture:

  1. LPR camera emits plate number + direction (enter/exit) + confidence + timestamp
  2. Normalize plate string (uppercase, remove spaces)
  3. Whitelist check → authorized: log + trigger gate relay; unauthorized: log + alert
  4. Pair entry/exit events → calculate dwell time
  5. Report: daily log, monthly summary, unauthorized attempts

Gate Control Integration: LPR match → HTTP POST to IP relay controller → 500ms relay trigger → barrier arm opens.


Consolidated System Architecture

Three services share the same SDK session pool and write to separate databases, all feeding a unified reporting dashboard. Video backup runs on a nightly schedule; face recognition and LPR run as always-on event listeners.

LayerTechnology
SDKDahua.Api + Dahua HTTP API
SchedulerHangfire or Quartz.NET
DatabasePostgreSQL / SQL Server
Event BusRabbitMQ (face/LPR event fan-out)
StorageNAS + Azure Blob / S3 archive tier
Gate ControlHTTP → IP relay (Wiegand/RS485 bridge)

Vendor Comparison

VendorSDKNotes
DahuaDahua.Api / NetSDKwin-x64 only; rich feature set
HikvisionHikVisionNet.OpenSDKSimilar architecture
AxisVAPIX HTTP RESTCross-platform; no proprietary lock-in
GenericONVIFCross-vendor standard; limited advanced features

Use ONVIF for multi-vendor environments, but face recognition and LPR still require vendor-specific APIs.

  • Dahua.Api — the C# SDK implementation
  • BLEAF — enterprise workflow system that could consume attendance records from Face Recognition