hikvision-isup / app.py
Lewis Kimaru
fix: improve ISUP parsing, dashboard auto-refresh, error handling, and add device config guide
e5c55d1
Raw History Blame Contribute Delete
16.6 kB
"""
Hikvision ISUP 5.0 Web Server (Refactored)
FastAPI integration with ISUP 5.0 binary protocol server, running in a single asyncio event loop.
"""
import asyncio
from datetime import datetime
from typing import List, Dict, Any, Optional
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, JSONResponse, Response
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
import logging
# Assume your ISUP server logic is in a file named isup5_server.py
# and it contains the ISUPServer class and AUTHORIZED_DEVICES dictionary.
from isup5_server import ISUP5Server, AUTHORIZED_DEVICES, DeviceCommands
# --- Logging Configuration ---
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# --- FastAPI App Initialization ---
app = FastAPI(
title="Hikvision ISUP 5.0 Server",
description="ISUP 5.0 Binary Protocol Server with Web Interface",
version="2.1.0"
)
templates = Jinja2Templates(directory="templates")
# --- Global ISUP Server Instance ---
# This single instance will be managed by FastAPI's lifecycle events.
isup_server = ISUP5Server(host="0.0.0.0", port=7660)
# --- Pydantic Response Models (for API documentation and validation) ---
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
class ServerStats(BaseModel):
server_running: bool
total_connections: int
active_devices: int
healthy_connections: int
authorized_devices: int
total_messages_processed: int
total_errors: int
error_rate: float
recent_events: int
attendance_records: int
class ConnectionDetail(BaseModel):
device_id: Optional[str]
address: str
status: str
authenticated: bool
connected_duration: str
last_heartbeat: str
message_count: int
error_count: int
last_error: Optional[str]
is_healthy: bool
class HealthCheckResponse(BaseModel):
status: str
server_stats: ServerStats
unhealthy_connections: List[dict]
timestamp: str
# --- FastAPI Lifecycle Events (Startup and Shutdown) ---
@app.on_event("startup")
async def startup_event():
"""
Start the ISUP TCP Server as an asyncio task in the main event loop
when the FastAPI application starts.
"""
logger.info("πŸš€ Starting ISUP TCP Server as a background task...")
try:
# Get the current running event loop from FastAPI/Uvicorn
loop = asyncio.get_running_loop()
# Schedule the server to run in the background
loop.create_task(isup_server.start())
logger.info("βœ… ISUP TCP Server has been scheduled to run.")
except Exception as e:
logger.error(f"❌ Critical error during ISUP server startup: {e}")
@app.on_event("shutdown")
async def shutdown_event():
"""
Gracefully stop the ISUP server when the FastAPI application shuts down.
"""
logger.info("πŸ›‘ Shutting down ISUP TCP Server...")
await isup_server.stop()
logger.info("βœ… ISUP TCP Server has been stopped.")
# --- Web Interface Routes ---
@app.get("/", response_class=HTMLResponse)
async def dashboard(request: Request):
"""Main dashboard to view device status and recent activity."""
connections = isup_server.get_connection_status()
recent_events = isup_server.get_recent_events(limit=10)
recent_attendance = isup_server.get_recent_attendance(limit=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": isup_server.port,
"authorized_devices": len(AUTHORIZED_DEVICES),
"status": "Running" if isup_server.is_running() else "Stopped"
}
})
# --- API Routes ---
@app.get("/api/health")
async def health_check():
"""Health check endpoint to verify service status."""
return {
"status": "healthy",
"isup_server": "running" if isup_server.is_running() else "stopped",
"timestamp": datetime.now().isoformat()
}
@app.get("/api/isup/connections", response_model=ConnectionStatus)
async def get_connections():
"""Get the status of all currently connected ISUP devices."""
return isup_server.get_connection_status()
@app.get("/api/events", response_model=EventResponse)
async def get_events(limit: int = 50):
"""Get a list of the most recent events from all devices."""
events_data = isup_server.get_recent_events(limit)
return EventResponse(events=events_data, total=len(events_data))
@app.get("/api/attendance", response_model=AttendanceResponse)
async def get_attendance(limit: int = 50):
"""Get a list of the most recent attendance records."""
attendance_data = isup_server.get_recent_attendance(limit)
return AttendanceResponse(attendance=attendance_data, total=len(attendance_data))
@app.post("/api/devices/{device_id}/open_door", response_model=CommandResponse)
async def open_door(device_id: str):
"""Send a command to remotely open a door connected to the specified 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 successfully.")
raise HTTPException(status_code=404, detail="Device not connected or command failed.")
@app.post("/api/devices/{device_id}/reboot", response_model=CommandResponse)
async def reboot_device(device_id: str):
"""Send a command to reboot the specified device."""
success = await isup_server.send_command_to_device(
device_id,
DeviceCommands.REBOOT
)
if success:
return CommandResponse(success=True, message="Reboot command sent successfully.")
raise HTTPException(status_code=404, detail="Device not connected or command failed.")
@app.get("/api/server/stats", response_model=ServerStats)
async def get_server_stats():
"""Get comprehensive server statistics."""
return isup_server.get_server_stats()
@app.get("/api/server/health", response_model=HealthCheckResponse)
async def get_server_health():
"""Get detailed server health information."""
return await isup_server.health_check()
@app.get("/api/connections/details", response_model=List[ConnectionDetail])
async def get_connection_details():
"""Get detailed information about all active connections."""
return isup_server.get_connection_details()
@app.get("/api/debug/connection-attempts")
async def get_connection_attempts():
"""Get all connection attempts for debugging."""
from isup5_server import connection_attempts
return {"connection_attempts": connection_attempts}
@app.get("/api/debug/raw-requests")
async def get_raw_requests():
"""Get all raw ISUP requests for debugging."""
from isup5_server import raw_requests
return {"raw_requests": raw_requests}
@app.get("/api/debug/registration-attempts")
async def get_registration_attempts():
"""Get all device registration attempts for debugging."""
from isup5_server import registration_attempts
return {"registration_attempts": registration_attempts}
@app.websocket("/ws/isup")
async def websocket_isup_tunnel(websocket: WebSocket):
"""WebSocket tunnel for ISUP protocol - allows devices to connect via WebSocket"""
await websocket.accept()
# Log WebSocket connection
client_ip = websocket.client.host if websocket.client else "unknown"
logger.info(f"πŸ”Œ WebSocket ISUP connection from {client_ip}")
# Add to connection attempts log
from isup5_server import connection_attempts
connection_attempt = {
"timestamp": datetime.now().isoformat(),
"source_ip": client_ip,
"source_port": websocket.client.port if websocket.client else 0,
"status": "websocket_accepted",
"user_agent": None,
"connection_type": "WebSocket"
}
connection_attempts.append(connection_attempt)
try:
while True:
# Receive binary data from WebSocket
data = await websocket.receive_bytes()
logger.info(f"πŸ“₯ Received {len(data)} bytes via WebSocket from {client_ip}")
# Process the ISUP data (simulate what TCP server would do)
response = await process_websocket_isup_data(data, client_ip)
if response:
# Send response back via WebSocket
await websocket.send_bytes(response)
logger.info(f"πŸ“€ Sent {len(response)} bytes via WebSocket to {client_ip}")
except WebSocketDisconnect:
logger.info(f"πŸ”Œ WebSocket disconnected: {client_ip}")
except Exception as e:
logger.error(f"❌ WebSocket error: {e}")
await websocket.close()
async def process_websocket_isup_data(data: bytes, client_ip: str) -> bytes:
"""Process ISUP data received via WebSocket"""
try:
# Import here to avoid circular imports
from isup5_server import ISUPMessage, ISUPMessageType, ISUP_VERSION, raw_requests
# Always log the raw request first
raw_request = {
"timestamp": datetime.now().isoformat(),
"source_ip": client_ip,
"source_port": 0, # WebSocket doesn't have traditional ports
"device_id": "unknown",
"message_type": "unknown",
"message_type_name": "UNPARSED",
"sequence": 0,
"data_length": len(data),
"raw_data_hex": data.hex() if data else "",
"raw_data_preview": get_data_preview(data),
"connection_status": "websocket"
}
# Try to parse as ISUP message
message = ISUPMessage()
logger.info(f"πŸ” Attempting to parse {len(data)} bytes from {client_ip}")
logger.info(f"πŸ” First 20 bytes: {data[:20].hex()}")
if len(data) >= 20 and message.unpack(data): # Minimum ISUP header size
# Update with parsed info
raw_request["device_id"] = message.header.device_id or "unknown"
raw_request["message_type"] = f"0x{message.header.message_type:02X}"
raw_request["message_type_name"] = get_message_type_name(message.header.message_type)
raw_request["sequence"] = message.header.sequence
logger.info(f"πŸ“¨ Successfully parsed ISUP message: {raw_request['message_type_name']} from {client_ip}")
# Process registration requests
if message.header.message_type == ISUPMessageType.REGISTER_REQ.value:
raw_requests.append(raw_request)
return await process_websocket_registration(message, client_ip)
else:
logger.warning(f"⚠️ Failed to parse ISUP message from {client_ip}: {len(data)} bytes")
if len(data) >= 20:
logger.warning(f"⚠️ Header parse failed - Version: 0x{data[0]:02X}, Type: 0x{data[1]:02X}")
raw_request["message_type_name"] = "PARSE_FAILED"
# Always log the request
raw_requests.append(raw_request)
# Keep only last 200 requests
if len(raw_requests) > 200:
raw_requests.pop(0)
return None
except Exception as e:
logger.error(f"❌ Error processing WebSocket ISUP data: {e}")
return None
def get_message_type_name(message_type: int) -> str:
"""Get human-readable message type name"""
type_names = {
0x01: "REGISTER_REQ", 0x81: "REGISTER_RSP",
0x02: "HEARTBEAT_REQ", 0x82: "HEARTBEAT_RSP",
0x03: "AUTH_REQ", 0x83: "AUTH_RSP",
0x04: "SESSIONKEY_REQ", 0x84: "SESSIONKEY_RSP",
0x05: "EVENT_REPORT", 0x85: "EVENT_ACK",
0x06: "COMMAND_REQ", 0x86: "COMMAND_RSP",
0x07: "BINARY_DATA", 0x87: "BINARY_ACK"
}
return type_names.get(message_type, f"UNKNOWN_0x{message_type:02X}")
def get_data_preview(data: bytes) -> str:
"""Get a preview of the data for logging"""
if not data:
return ""
try:
text_preview = data[:100].decode('utf-8', errors='ignore')
return f"Text: {text_preview[:50]}{'...' if len(text_preview) > 50 else ''}"
except:
hex_preview = data[:20].hex()
return f"Hex: {hex_preview}{'...' if len(data) > 20 else ''}"
async def process_websocket_registration(message, client_ip: str) -> bytes:
"""Process registration request via WebSocket"""
from isup5_server import ISUPMessage, ISUPMessageType, ISUP_VERSION, registration_attempts
# Log registration attempt
registration_attempt = {
"timestamp": datetime.now().isoformat(),
"source_ip": client_ip,
"source_port": 0,
"data_length": len(message.data),
"raw_data_hex": message.data.hex() if message.data else "",
"status": "websocket_attempting",
"device_id": message.header.device_id,
"serial_number": None,
"error_message": None
}
registration_attempts.append(registration_attempt)
# Create response
response = ISUPMessage()
response.header.version = ISUP_VERSION
response.header.message_type = ISUPMessageType.REGISTER_RSP.value
response.header.sequence = message.header.sequence + 1
response.header.device_id = message.header.device_id
# Simple success response for WebSocket testing
response.data = b'\x00\x18WebSocket registration test'
registration_attempt["status"] = "websocket_success"
return response.pack()
@app.post("/api/isup/tunnel")
async def http_isup_tunnel(request: Request):
"""HTTP tunnel for ISUP protocol - allows devices to send ISUP data via HTTP POST"""
try:
# Get client IP
client_ip = request.client.host if request.client else "unknown"
# Read raw binary data from request body
data = await request.body()
logger.info(f"πŸ“₯ Received {len(data)} bytes via HTTP tunnel from {client_ip}")
# Log connection attempt
from isup5_server import connection_attempts
connection_attempt = {
"timestamp": datetime.now().isoformat(),
"source_ip": client_ip,
"source_port": 0,
"status": "http_tunnel",
"user_agent": request.headers.get("user-agent"),
"connection_type": "HTTP"
}
connection_attempts.append(connection_attempt)
# Process the ISUP data
response_data = await process_websocket_isup_data(data, client_ip)
if response_data:
# Return binary response
return Response(content=response_data, media_type="application/octet-stream")
else:
return {"status": "processed", "message": "ISUP data received"}
except Exception as e:
logger.error(f"❌ HTTP tunnel error: {e}")
raise HTTPException(status_code=500, detail=f"Error processing ISUP data: {str(e)}")
# --- Error Handlers for API Robustness ---
@app.exception_handler(404)
async def not_found_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=404,
content={"error": "Resource Not Found", "detail": str(exc.detail)}
)
@app.exception_handler(Exception)
async def general_exception_handler(request: Request, exc: Exception):
logger.error(f"An unhandled exception occurred: {exc}", exc_info=True)
return JSONResponse(
status_code=500,
content={"error": "Internal Server Error", "detail": "An unexpected error occurred."}
)
# --- Main execution block (for running with `python app.py`) ---
if __name__ == "__main__":
import uvicorn
print("============================================================")
print("πŸš€ Starting Hikvision ISUP 5.0 Web Server...")
print(f"πŸ”§ Protocol: ISUP 5.0 Binary")
print(f"πŸ“‘ ISUP Server Port: TCP {isup_server.port}")
print(f"🌐 Web Interface: http://0.0.0.0:7860")
print("============================================================")
uvicorn.run(
"app:app", # Point to this file's app instance
host="0.0.0.0",
port=7860,
reload=False, # Important: Keep reload False in production
log_level="info"
)