Spaces:
Runtime error
Runtime error
File size: 7,447 Bytes
7566eb5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | """
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"
)
|