hikvision-isup / docs /dev /app_isup5.py
Lewis Kimaru
Refactor to single app.py for ISUP5.0
7566eb5
Raw History Blame Contribute Delete
7.45 kB
"""
Hikvision ISUP 5.0 Web Server
FastAPI integration with ISUP 5.0 binary protocol server
"""
import asyncio
import threading
from datetime import datetime
from typing import List, Dict, Any
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
from isup5_server import isup_server, DeviceCommands, AUTHORIZED_DEVICES
# FastAPI App
app = FastAPI(
title="Hikvision ISUP 5.0 Server",
description="ISUP 5.0 Binary Protocol Server with Web Interface",
version="2.0.0"
)
templates = Jinja2Templates(directory="templates")
# Response Models
class ConnectionStatus(BaseModel):
total_connections: int
active_connections: int
devices: List[Dict[str, Any]]
class EventResponse(BaseModel):
events: List[Dict[str, Any]]
total: int
class AttendanceResponse(BaseModel):
attendance: List[Dict[str, Any]]
total: int
class CommandResponse(BaseModel):
success: bool
message: str
# Global ISUP server thread
isup_thread = None
isup_running = False
def start_isup_server():
"""Start ISUP server in background thread"""
global isup_running
isup_running = True
# Create new event loop for the thread
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(isup_server.start())
except Exception as e:
print(f"ISUP server error: {e}")
finally:
isup_running = False
@app.on_event("startup")
async def startup_event():
"""Start ISUP server on FastAPI startup"""
global isup_thread
print("πŸš€ Starting ISUP 5.0 Server...")
isup_thread = threading.Thread(target=start_isup_server, daemon=True)
isup_thread.start()
# Give server time to start
await asyncio.sleep(1)
print("βœ… ISUP 5.0 Server started in background")
@app.on_event("shutdown")
async def shutdown_event():
"""Cleanup on shutdown"""
global isup_running
isup_running = False
print("πŸ›‘ ISUP 5.0 Server shutting down...")
# Web Interface Routes
@app.get("/", response_class=HTMLResponse)
async def dashboard(request: Request):
"""Main dashboard"""
# Get current data
connections = isup_server.get_connection_status()
recent_events = isup_server.get_recent_events(10)
recent_attendance = isup_server.get_recent_attendance(10)
return templates.TemplateResponse("dashboard.html", {
"request": request,
"devices": connections['devices'],
"recent_events": recent_events,
"recent_attendance": recent_attendance,
"server_info": {
"protocol": "ISUP 5.0",
"port": 7660,
"authorized_devices": len(AUTHORIZED_DEVICES),
"status": "Running" if isup_running else "Stopped"
}
})
# API Routes
@app.get("/api/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"isup_server": "running" if isup_running else "stopped",
"timestamp": datetime.now().isoformat()
}
@app.get("/api/isup/connections", response_model=ConnectionStatus)
async def get_connections():
"""Get ISUP connection status"""
return isup_server.get_connection_status()
@app.get("/api/events", response_model=EventResponse)
async def get_events(limit: int = 50):
"""Get recent events"""
events = isup_server.get_recent_events(limit)
return EventResponse(events=events, total=len(events))
@app.get("/api/attendance", response_model=AttendanceResponse)
async def get_attendance(limit: int = 50):
"""Get recent attendance records"""
attendance = isup_server.get_recent_attendance(limit)
return AttendanceResponse(attendance=attendance, total=len(attendance))
@app.post("/api/devices/{device_id}/open_door", response_model=CommandResponse)
async def open_door(device_id: str):
"""Send door open command to device"""
success = await isup_server.send_command_to_device(
device_id,
DeviceCommands.OPEN_DOOR
)
if success:
return CommandResponse(success=True, message="Door open command sent")
else:
raise HTTPException(status_code=404, detail="Device not found or not connected")
@app.post("/api/devices/{device_id}/capture_face", response_model=CommandResponse)
async def capture_face(device_id: str):
"""Send face capture command to device"""
success = await isup_server.send_command_to_device(
device_id,
DeviceCommands.CAPTURE_FACE
)
if success:
return CommandResponse(success=True, message="Face capture command sent")
else:
raise HTTPException(status_code=404, detail="Device not found or not connected")
@app.post("/api/devices/{device_id}/reboot", response_model=CommandResponse)
async def reboot_device(device_id: str):
"""Send reboot command to device"""
success = await isup_server.send_command_to_device(
device_id,
DeviceCommands.REBOOT
)
if success:
return CommandResponse(success=True, message="Reboot command sent")
else:
raise HTTPException(status_code=404, detail="Device not found or not connected")
@app.get("/api/devices/{device_id}/status")
async def get_device_status(device_id: str):
"""Get device status"""
connections = isup_server.get_connection_status()
for device in connections['devices']:
if device['device_id'] == device_id:
return device
raise HTTPException(status_code=404, detail="Device not found")
@app.get("/api/config/devices")
async def get_device_config():
"""Get authorized device configuration"""
return {
"authorized_devices": AUTHORIZED_DEVICES,
"total": len(AUTHORIZED_DEVICES)
}
@app.get("/api/protocol/info")
async def get_protocol_info():
"""Get ISUP protocol information"""
return {
"protocol": "ISUP",
"version": "5.0",
"binary_protocol": True,
"authentication": "EHome Key + Session Key",
"port": 7660,
"features": [
"Binary message format",
"ISUP 5.0 authentication flow",
"Session key management",
"Real-time event processing",
"Device command support",
"Temperature screening",
"Mask detection",
"Multiple verification modes"
]
}
# Error handlers
@app.exception_handler(404)
async def not_found_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=404,
content={"error": "Not found", "detail": str(exc.detail)}
)
@app.exception_handler(500)
async def internal_error_handler(request: Request, exc: Exception):
return JSONResponse(
status_code=500,
content={"error": "Internal server error", "detail": str(exc)}
)
if __name__ == "__main__":
import uvicorn
print("πŸš€ Starting Hikvision ISUP 5.0 Web Server...")
print("πŸ“‹ Protocol: ISUP 5.0 Binary")
print("πŸ”§ Authentication: EHome Key + Session Key")
print("🌐 Web Interface: http://localhost:7860")
print("πŸ“‘ ISUP Server: TCP port 7660")
uvicorn.run(
"app_isup5:app",
host="0.0.0.0",
port=7860,
reload=False, # Disable reload to prevent ISUP server restart issues
log_level="info"
)