Tóm tắt: Bài viết này hướng dẫn bạn xây dựng hệ thống IoT giám sát bể nước phòng cháy chữa cháy (PCCC) thông minh, kết hợp khả năng nhận diện hình ảnh từ GPT-4o để đo mực nước theo thời gian thực và DeepSeek V3.2 để phân tích dữ liệu bảo trì dự đoán. Với HolySheep AI, chi phí vận hành chỉ từ $0.42/MTok (DeepSeek), tiết kiệm đến 85%+ so với API chính thức, độ trễ dưới 50ms.

Mục lục

Giới thiệu hệ thống IoT giám sát bể nước PCCC

Trong lĩnh vực phòng cháy chữa cháy hiện đại, việc giám sát mực nước bể chữa cháy là yêu cầu bắt buộc theo TCVN 6161:2009 và các quy chuẩn PCCC quốc gia. Tuy nhiên, phương pháp kiểm tra thủ công truyền thống gặp nhiều hạn chế:

Hệ thống HolySheep 智慧消防水箱物联 Agent giải quyết các vấn đề này bằng cách kết hợp:

Kiến trúc hệ thống

Hệ thống gồm 3 tầng chính:

┌─────────────────────────────────────────────────────────────┐
│                    TẦNG IoT CẢM BIẾN                        │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐     │
│  │ Camera 1 │  │ Camera 2 │  │  Sensor  │  │  Sensor  │     │
│  │ (Tank A) │  │ (Tank B) │  │  Level 1 │  │  Level 2 │     │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘  └────┬─────┘     │
│       │             │             │             │            │
└───────┼─────────────┼─────────────┼─────────────┼────────────┘
        │             │             │             │
        ▼             ▼             ▼             ▼
┌─────────────────────────────────────────────────────────────┐
│                    TẦNG XỬ LÝ TRUNG TÂM                     │
│  ┌─────────────────────────────────────────────────────┐     │
│  │         HolySheep AI Gateway (Edge Device)          │     │
│  │  ┌─────────────┐    ┌─────────────┐                 │     │
│  │  │  GPT-4o     │    │  DeepSeek   │                 │     │
│  │  │  Image Rec. │    │  V3.2       │                 │     │
│  │  │  $8/MTok    │    │  $0.42/MTok │                 │     │
│  │  └─────────────┘    └─────────────┘                 │     │
│  └─────────────────────────────────────────────────────┘     │
└─────────────────────────────────────────────────────────────┘
        │
        ▼
┌─────────────────────────────────────────────────────────────┐
│                    TẦNG ĐÁM MÂY / Dashboard                  │
│     ┌──────────┐  ┌──────────┐  ┌──────────┐                │
│     │ Alert    │  │ History  │  │ Report   │                │
│     │ System   │  │ DB       │  │ Engine   │                │
│     └──────────┘  └──────────┘  └──────────┘                │
└─────────────────────────────────────────────────────────────┘

Cài đặt và cấu hình môi trường

Yêu cầu hệ thống

Cài đặt thư viện

pip install opencv-python requests Pillow python-dotenv

Code ví dụ đầy đủ — Water Tank IoT Agent

1. Cấu hình kết nối HolySheep API

import os
import base64
import json
import time
import requests
from datetime import datetime
import cv2
from io import BytesIO

============================================================

CẤU HÌNH HOLYSHEEP API -智慧消防水箱物联 Agent

Base URL: https://api.holysheep.ai/v1

API Key: YOUR_HOLYSHEEP_API_KEY

============================================================

HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1" HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY" # Thay bằng API key của bạn

Headers xác thực

HEADERS = { "Authorization": f"Bearer {HOLYSHEEP_API_KEY}", "Content-Type": "application/json" } def test_connection(): """Kiểm tra kết nối HolySheep API""" try: response = requests.get( f"{HOLYSHEEP_BASE_URL}/models", headers=HEADERS, timeout=10 ) if response.status_code == 200: models = response.json().get("data", []) print("✅ Kết nối HolySheep API thành công!") print(f"📊 Số lượng mô hình khả dụng: {len(models)}") return True else: print(f"❌ Lỗi: {response.status_code}") return False except Exception as e: print(f"❌ Lỗi kết nối: {e}") return False

Test kết nối khi chạy script

if __name__ == "__main__": test_connection()

2. GPT-4o nhận diện mực nước từ hình ảnh camera

import base64
import json
import time
import requests
import cv2
import numpy as np
from datetime import datetime

HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY"

def encode_image_to_base64(image_array):
    """Mã hóa OpenCV image thành base64"""
    _, buffer = cv2.imencode('.jpg', image_array)
    return base64.b64encode(buffer).decode('utf-8')

def detect_water_level_gpt4o(image_path_or_array):
    """
    Sử dụng GPT-4o để nhận diện mực nước từ hình ảnh
    Chi phí: $8/MTok (tiết kiệm 85%+ so với API chính thức)
    """
    # Xử lý đầu vào
    if isinstance(image_path_or_array, str):
        image = cv2.imread(image_path_or_array)
    else:
        image = image_path_or_array
    
    if image is None:
        raise ValueError("Không thể đọc hình ảnh")
    
    # Chuyển đổi sang base64
    base64_image = encode_image_to_base64(image)
    
    # Prompt nhận diện mực nước
    prompt = """Bạn là chuyên gia phân tích hình ảnh bể nước PCCC.
    Phân tích hình ảnh và trả về JSON với các trường:
    - water_level_percent: % mực nước (0-100)
    - status: "normal" | "low" | "critical" | "overflow"
    - anomalies: danh sách các bất thường (rỉ rỉ, bẩn, vật cản)
    - timestamp: thời gian phân tích ISO format
    - confidence: độ tin cậy (0.0-1.0)
    
    Ví dụ output:
    {"water_level_percent": 75, "status": "normal", 
     "anomalies": [], "timestamp": "2026-05-24T22:51:00Z", 
     "confidence": 0.95}"""
    
    # Gọi GPT-4o qua HolySheep
    start_time = time.time()
    
    payload = {
        "model": "gpt-4o",
        "messages": [
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": prompt},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{base64_image}"
                        }
                    }
                ]
            }
        ],
        "max_tokens": 500,
        "temperature": 0.1
    }
    
    try:
        response = requests.post(
            f"{HOLYSHEEP_BASE_URL}/chat/completions",
            headers={
                "Authorization": f"Bearer {HOLYSHEEP_API_KEY}",
                "Content-Type": "application/json"
            },
            json=payload,
            timeout=30
        )
        
        latency_ms = (time.time() - start_time) * 1000
        
        if response.status_code == 200:
            result = response.json()
            content = result["choices"][0]["message"]["content"]
            
            # Parse JSON từ response
            # GPT-4o có thể trả về markdown code block
            if "```json" in content:
                content = content.split("``json")[1].split("``")[0]
            elif "```" in content:
                content = content.split("``")[1].split("``")[0]
            
            water_data = json.loads(content.strip())
            water_data["latency_ms"] = round(latency_ms, 2)
            water_data["model"] = "gpt-4o"
            
            print(f"📊 Water Level: {water_data['water_level_percent']}%")
            print(f"⏱️ Latency: {latency_ms:.2f}ms")
            print(f"🎯 Status: {water_data['status']}")
            
            return water_data
        else:
            raise Exception(f"API Error: {response.status_code}")
            
    except Exception as e:
        print(f"❌ Lỗi nhận diện: {e}")
        return None

def continuous_monitoring(camera_id, interval_seconds=60):
    """Giám sát liên tục mực nước"""
    cap = cv2.VideoCapture(camera_id)
    readings = []
    
    print(f"🔄 Bắt đầu giám sát Camera {camera_id}...")
    
    try:
        while True:
            ret, frame = cap.read()
            if not ret:
                print("❌ Không nhận được frame từ camera")
                break
            
            result = detect_water_level_gpt4o(frame)
            if result:
                readings.append(result)
                
                # Cảnh báo nếu mực nước thấp
                if result["water_level_percent"] < 30:
                    print(f"🚨 CẢNH BÁO: Mực nước thấp {result['water_level_percent']}%!")
                
                # Gửi cảnh báo critical
                if result["status"] == "critical":
                    print(f"🚨🚨 Nguy hiểm: Cạn kiệt nước!")
            
            time.sleep(interval_seconds)
            
    finally:
        cap.release()
        return readings

Test nhanh

if __name__ == "__main__": # Giả lập test với ảnh mẫu test_image = cv2.imread("test_water_tank.jpg") # Thay bằng ảnh thực tế if test_image is not None: result = detect_water_level_gpt4o(test_image) print(json.dumps(result, indent=2))

3. DeepSeek V3.2 phân tích bảo trì dự đoán

import requests
import time
import json
from datetime import datetime, timedelta
from typing import List, Dict

HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY"

def predict_maintenance_deepseek(water_readings: List[Dict]) -> Dict:
    """
    Sử dụng DeepSeek V3.2 ($0.42/MTok) để phân tích bảo trì dự đoán
    Chi phí cực thấp, phù hợp xử lý batch data lớn
    """
    
    # Tổng hợp dữ liệu lịch sử
    summary = {
        "total_readings": len(water_readings),
        "avg_level": sum(r["water_level_percent"] for r in water_readings) / len(water_readings) if water_readings else 0,
        "min_level": min((r["water_level_percent"] for r in water_readings), default=0),
        "max_level": max((r["water_level_percent"] for r in water_readings), default=0),
        "critical_events": sum(1 for r in water_readings if r["status"] == "critical"),
        "anomalies_detected": []
    }
    
    # Thu thập anomalies
    for reading in water_readings:
        summary["anomalies_detected"].extend(reading.get("anomalies", []))
    
    # Prompt cho DeepSeek phân tích bảo trì
    prompt = f"""Bạn là chuyên gia bảo trì hệ thống PCCC (Phòng cháy chữa cháy).
    Phân tích dữ liệu cảm biến và đưa ra khuyến nghị bảo trì:
    
    Dữ liệu tổng hợp:
    - Tổng số lần đọc: {summary['total_readings']}
    - Mực nước trung bình: {summary['avg_level']:.1f}%
    - Mực nước thấp nhất: {summary['min_level']:.1f}%
    - Mực nước cao nhất: {summary['max_level']:.1f}%
    - Số sự kiện nguy hiểm: {summary['critical_events']}
    - Các bất thường: {summary['anomalies_detected']}
    
    Trả về JSON:
    {{
        "maintenance_score": 0-100 (điểm sức khỏe hệ thống),
        "risk_level": "low" | "medium" | "high" | "critical",
        "predicted_next_issue": "Mô tả vấn đề dự đoán",
        "days_until_maintenance": số ngày,
        "recommendations": ["Khuyến nghị 1", "Khuyến nghị 2"],
        "urgency": "routine" | "scheduled" | "soon" | "immediate"
    }}"""
    
    start_time = time.time()
    
    payload = {
        "model": "deepseek-v3.2",
        "messages": [
            {"role": "system", "content": "Bạn là chuyên gia phân tích bảo trì PCCC."},
            {"role": "user", "content": prompt}
        ],
        "max_tokens": 800,
        "temperature": 0.3
    }
    
    try:
        response = requests.post(
            f"{HOLYSHEEP_BASE_URL}/chat/completions",
            headers={
                "Authorization": f"Bearer {HOLYSHEEP_API_KEY}",
                "Content-Type": "application/json"
            },
            json=payload,
            timeout=30
        )
        
        latency_ms = (time.time() - start_time) * 1000
        
        if response.status_code == 200:
            result = response.json()
            content = result["choices"][0]["message"]["content"]
            
            # Parse JSON
            if "```json" in content:
                content = content.split("``json")[1].split("``")[0]
            elif "```" in content:
                content = content.split("``")[1].split("``")[0]
            
            analysis = json.loads(content.strip())
            analysis["latency_ms"] = round(latency_ms, 2)
            analysis["cost_estimate"] = "$0.000042"  # ~100 tokens * $0.42/MTok
            
            return analysis
        else:
            raise Exception(f"API Error: {response.status_code}")
            
    except Exception as e:
        print(f"❌ Lỗi phân tích bảo trì: {e}")
        return None

def generate_maintenance_report(water_readings: List[Dict]) -> str:
    """Tạo báo cáo bảo trì đầy đủ"""
    analysis = predict_maintenance_deepseek(water_readings)
    
    if not analysis:
        return "Không thể tạo báo cáo"
    
    report = f"""
╔══════════════════════════════════════════════════════════╗
║           BÁO CÁO BẢO TRÌ HỆ THỐNG PCCC                  ║
║           Smart Fire Tank IoT Agent Report                ║
╠══════════════════════════════════════════════════════════╣
║ Ngày tạo: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
║──────────────────────────────────────────────────────────║
║ 📊 Điểm sức khỏe: {analysis['maintenance_score']}/100
║ ⚠️ Mức rủi ro: {analysis['risk_level'].upper()}
║ ⏱️ Latency: {analysis['latency_ms']}ms
║ 💰 Chi phí phân tích: {analysis['cost_estimate']}
╠══════════════════════════════════════════════════════════╣
║ 📅 Dự đoán bảo trì: {analysis['days_until_maintenance']} ngày
║ 🎯 Vấn đề dự đoán: {analysis['predicted_next_issue']}
║ 🚨 Độ khẩn cấp: {analysis['urgency'].upper()}
╠══════════════════════════════════════════════════════════╣
║ 📋 Khuyến nghị:
"""
    
    for i, rec in enumerate(analysis["recommendations"], 1):
        report += f"║   {i}. {rec}\n"
    
    report += "╚══════════════════════════════════════════════════════════╝"
    
    return report

Demo sử dụng

if __name__ == "__main__": # Mock data cho demo mock_readings = [ {"water_level_percent": 85, "status": "normal", "anomalies": [], "timestamp": "2026-05-20T10:00:00Z"}, {"water_level_percent": 82, "status": "normal", "anomalies": ["Sụt nhẹ"], "timestamp": "2026-05-21T10:00:00Z"}, {"water_level_percent": 78, "status": "normal", "anomalies": [], "timestamp": "2026-05-22T10:00:00Z"}, {"water_level_percent": 65, "status": "low", "anomalies": ["Sụt bất thường"], "timestamp": "2026-05-23T10:00:00Z"}, {"water_level_percent": 35, "status": "critical", "anomalies": ["Rò rỉ nghiêm trọng"], "timestamp": "2026-05-24T10:00:00Z"}, ] analysis = predict_maintenance_deepseek(mock_readings) print(generate_maintenance_report(mock_readings))

4. Unified API Key Monitoring Dashboard

import requests
import time
from datetime import datetime
from typing import Dict, List

HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
HOLYSHEEP_API_KEY = "YOUR_HOLYSHEEP_API_KEY"

class HolySheepMonitor:
    """Giám sát usage và chi phí API unified"""
    
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.usage_log = []
        
    def get_usage_stats(self) -> Dict:
        """Lấy thống kê sử dụng từ HolySheep API"""
        headers = {"Authorization": f"Bearer {self.api_key}"}
        
        try:
            # Lấy thông tin tài khoản
            response = requests.get(
                f"{HOLYSHEEP_BASE_URL}/account",
                headers=headers,
                timeout=10
            )
            
            if response.status_code == 200:
                return response.json()
            else:
                return {"error": f"Status {response.status_code}"}
                
        except Exception as e:
            return {"error": str(e)}
    
    def estimate_cost(self, model: str, input_tokens: int, output_tokens: int) -> Dict:
        """Ước tính chi phí theo model"""
        pricing = {
            "gpt-4o": 8.00,           # $/MTok
            "deepseek-v3.2": 0.42,   # $/MTok
            "claude-sonnet-4.5": 15.00,
            "gemini-2.5-flash": 2.50
        }
        
        price_per_mtok = pricing.get(model, 8.00)
        total_tokens = input_tokens + output_tokens
        cost = (total_tokens / 1_000_000) * price_per_mtok
        
        # So sánh với API chính thức
        official_pricing = {
            "gpt-4o": 5.00 + 15.00,  # Input + Output OpenAI
            "deepseek-v3.2": 0.27 + 1.10,  # Ước tính
        }
        
        official_cost = (total_tokens / 1_000_000) * (official_pricing.get(model, 20.00))
        savings = official_cost - cost
        
        return {
            "model": model,
            "total_tokens": total_tokens,
            "holysheep_cost": round(cost, 6),
            "official_estimate": round(official_cost, 6),
            "savings_percent": round((savings / official_cost * 100), 1) if official_cost > 0 else 0,
            "savings_usd": round(savings, 6)
        }
    
    def simulate_fire_tank_monitoring(self, days: int = 30) -> Dict:
        """Mô phỏng chi phí giám sát bể nước PCCC trong N ngày"""
        
        # Giả định: 1 camera, đọc mỗi 5 phút, 24h
        readings_per_day = 288  # 12 * 24
        gpt4o_calls = readings_per_day * days  # GPT-4o cho mỗi ảnh
        
        # DeepSeek: 1 lần phân tích tổng hợp/ngày
        deepseek_calls = days
        
        # Ước tính tokens trung bình
        avg_tokens_per_gpt4o = 500  # Prompt + response
        avg_tokens_per_deepseek = 800
        
        # Tính chi phí HolySheep
        gpt4o_cost = (gpt4o_calls * avg_tokens_per_gpt4o / 1_000_000) * 8.00
        deepseek_cost = (deepseek_calls * avg_tokens_per_deepseek / 1_000_000) * 0.42
        
        total_holysheep = gpt4o_cost + deepseek_cost
        
        # So sánh với OpenAI Direct
        gpt4o_official = (gpt4o_calls * avg_tokens_per_gpt4o / 1_000_000) * 20.00
        total_official = gpt4o_official
        
        return {
            "scenario": f"Fire Tank Monitoring - {days} days",
            "gpt4o_calls": gpt4o_calls,
            "deepseek_calls": deepseek_calls,
            "holysheep_total_usd": round(total_holysheep, 2),
            "official_estimate_usd": round(total_official, 2),
            "total_savings_usd": round(total_official - total_holysheep, 2),
            "savings_percent": round((total_official - total_holysheep) / total_official * 100, 1),
            "breakdown": {
                "gpt4o_cost": round(gpt4o_cost, 4),
                "deepseek_cost": round(deepseek_cost, 4)
            }
        }

def run_cost_comparison():
    """So sánh chi phí HolySheep vs Official API"""
    
    print("=" * 70)
    print("SO SÁNH CHI PHÍ: HOLYSHEEP vs API CHÍNH THỨC")
    print("=" * 70)
    
    scenarios = [
        ("1 Camera, 30 ngày", 30),
        ("5 Cameras, 30 ngày", 30),
        ("10 Cameras, 30 ngày", 30),
        ("5 Cameras, 1 năm (365 ngày)", 365),
    ]
    
    results = []
    monitor = HolySheepMonitor(HOLYSHEEP_API_KEY)
    
    for name, days in scenarios:
        result = monitor.simulate_fire_tank_monitoring(days)
        result["scenario"] = name
        results.append(result)
        
        print(f"\n📊 {name}")
        print(f"   HolySheep: ${result['holysheep_total_usd']}")
        print(f"   Official:  ${result['official_estimate_usd']}")
        print(f"   💰 Tiết kiệm: ${result['total_savings_usd']} ({result['savings_percent']}%)")
    
    return results

if __name__ == "__main__":
    results = run_cost_comparison()

Bảng giá và so sánh chi tiết

Mô hình HolySheep ($/MTok) API Chính thức ($/MTok) Tiết kiệm Độ trễ Phương thức thanh toán Nhóm phù hợp
GPT-4o $8.00 $15.00 - $30.00 47% - 73% <50ms WeChat, Alipay, USD Vision tasks, nhận diện hình ảnh phức tạp
DeepSeek V3.2 $0.42 $0.27 - $1.10 -55% - 62% <50ms WeChat, Alipay, USD Phân tích dữ liệu, bảo trì dự đoán, batch processing
Claude Sonnet 4.5 $15.00 $15.00 - $18.00 0% - 17% <80ms WeChat, Alipay, USD Task phân tích chuyên sâu, reasoning phức tạp
Gemini 2.5 Flash $2.50 $0.30 - $1.25 -100% - 100% <40ms WeChat, Alipay, USD Xử lý nhanh, chi phí thấp, high-volume tasks

Bảng giá chi tiết theo kịch bản sử dụng

Tài nguyên liên quan

Bài viết liên quan

🔥 Thử HolySheep AI

Cổng AI API trực tiếp. Hỗ trợ Claude, GPT-5, Gemini, DeepSeek — một khóa, không cần VPN.

👉 Đăng ký miễn phí →

Kịch bản Số lượng camera Thời gian HolySheep ($) API Chính thức ($) ROI HolySheep
Smaller Project 1 30 ngày $1.15 $6.91 +83%