hikvision-isup / test /test_dashboard_refresh.py
Lewis Kimaru
fix: improve ISUP parsing, dashboard auto-refresh, error handling, and add device config guide
e5c55d1
Raw History Blame Contribute Delete
5.19 kB
#!/usr/bin/env python3
"""
Test Dashboard Refresh
Sends multiple requests and checks if dashboard updates
"""
import asyncio
import websockets
import requests
import time
import struct
# Configuration
HF_SPACE_URL = "atomio-hikvision-isup.hf.space"
WEBSOCKET_URL = f"wss://{HF_SPACE_URL}/ws/isup"
HTTP_TUNNEL_URL = f"https://{HF_SPACE_URL}/api/isup/tunnel"
DEBUG_URL = f"https://{HF_SPACE_URL}/api/debug"
def create_test_isup_message(device_id="TEST_DEVICE_123", sequence=1):
"""Create a test ISUP registration message"""
registration_data = f"FAKE_REGISTRATION_DATA_{sequence}".encode() + b"\x00" * 50
# Create ISUP header
header = struct.pack('>BBHB32sHH',
0x50, # ISUP version 5.0
0x01, # REGISTER_REQ
sequence, # sequence
len(device_id), # device_id_len
device_id.encode('utf-8').ljust(32, b'\x00'), # device_id
len(registration_data), # data_length
0 # reserved
)
return header + registration_data
async def send_websocket_messages(count=3):
"""Send multiple WebSocket messages"""
print(f"πŸ“€ Sending {count} WebSocket messages...")
for i in range(count):
try:
message = create_test_isup_message(f"WS_DEVICE_{i}", i+1)
async with websockets.connect(WEBSOCKET_URL) as websocket:
await websocket.send(message)
print(f"βœ… WebSocket message {i+1} sent")
await asyncio.sleep(1) # Wait between messages
except Exception as e:
print(f"❌ WebSocket message {i+1} failed: {e}")
def send_http_messages(count=3):
"""Send multiple HTTP messages"""
print(f"πŸ“€ Sending {count} HTTP messages...")
for i in range(count):
try:
message = create_test_isup_message(f"HTTP_DEVICE_{i}", i+10)
response = requests.post(
HTTP_TUNNEL_URL,
data=message,
headers={'Content-Type': 'application/octet-stream'},
timeout=10
)
if response.status_code == 200:
print(f"βœ… HTTP message {i+1} sent")
else:
print(f"❌ HTTP message {i+1} failed: {response.status_code}")
time.sleep(1) # Wait between messages
except Exception as e:
print(f"❌ HTTP message {i+1} failed: {e}")
def check_debug_data():
"""Check debug endpoints for data"""
print("\nπŸ” Checking debug data...")
try:
# Check connection attempts
response = requests.get(f"{DEBUG_URL}/connection-attempts")
if response.status_code == 200:
data = response.json()
attempts = data.get('connection_attempts', [])
print(f"πŸ“Š Connection attempts: {len(attempts)}")
# Show recent attempts
for attempt in attempts[-5:]:
print(f" {attempt['timestamp']}: {attempt['connection_type']} from {attempt['source_ip']}")
# Check registration attempts
response = requests.get(f"{DEBUG_URL}/registration-attempts")
if response.status_code == 200:
data = response.json()
attempts = data.get('registration_attempts', [])
print(f"πŸ“Š Registration attempts: {len(attempts)}")
for attempt in attempts[-3:]:
print(f" {attempt['timestamp']}: {attempt['status']} - {attempt.get('device_id', 'unknown')}")
# Check raw requests
response = requests.get(f"{DEBUG_URL}/raw-requests")
if response.status_code == 200:
data = response.json()
requests_data = data.get('raw_requests', [])
print(f"πŸ“Š Raw requests: {len(requests_data)}")
for req in requests_data[-3:]:
print(f" {req['timestamp']}: {req['message_type_name']} from {req['source_ip']}")
return True
except Exception as e:
print(f"❌ Error checking debug data: {e}")
return False
async def main():
"""Run dashboard refresh test"""
print("πŸ§ͺ Testing Dashboard Refresh Functionality")
print("=" * 50)
# Initial check
print("πŸ“Š Initial state:")
check_debug_data()
print(f"\n⏰ Waiting 3 seconds...")
await asyncio.sleep(3)
# Send WebSocket messages
await send_websocket_messages(3)
print(f"\n⏰ Waiting 2 seconds...")
await asyncio.sleep(2)
# Send HTTP messages
send_http_messages(3)
print(f"\n⏰ Waiting 2 seconds for processing...")
await asyncio.sleep(2)
# Final check
print("\nπŸ“Š Final state:")
check_debug_data()
print("\n" + "=" * 50)
print("🎯 Test Complete!")
print(f"πŸ’‘ Check the dashboard: https://{HF_SPACE_URL}/#debug")
print(" The debug tab should show the new connection attempts and messages.")
print(" If it doesn't update automatically, click 'Refresh Debug Data'.")
if __name__ == "__main__":
asyncio.run(main())