Lewis Kimaru commited on
Commit
ecf78bb
Β·
1 Parent(s): 4b80cde

fix: intergrate ISAPI with ISUP

Browse files
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
app.py CHANGED
@@ -52,6 +52,36 @@ class CommandResponse(BaseModel):
52
  success: bool
53
  message: str
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  # --- FastAPI Lifecycle Events (Startup and Shutdown) ---
56
 
57
  @app.on_event("startup")
@@ -151,6 +181,39 @@ async def reboot_device(device_id: str):
151
  return CommandResponse(success=True, message="Reboot command sent successfully.")
152
  raise HTTPException(status_code=404, detail="Device not connected or command failed.")
153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  # --- Error Handlers for API Robustness ---
155
 
156
  @app.exception_handler(404)
 
52
  success: bool
53
  message: str
54
 
55
+ class ServerStats(BaseModel):
56
+ server_running: bool
57
+ total_connections: int
58
+ active_devices: int
59
+ healthy_connections: int
60
+ authorized_devices: int
61
+ total_messages_processed: int
62
+ total_errors: int
63
+ error_rate: float
64
+ recent_events: int
65
+ attendance_records: int
66
+
67
+ class ConnectionDetail(BaseModel):
68
+ device_id: Optional[str]
69
+ address: str
70
+ status: str
71
+ authenticated: bool
72
+ connected_duration: str
73
+ last_heartbeat: str
74
+ message_count: int
75
+ error_count: int
76
+ last_error: Optional[str]
77
+ is_healthy: bool
78
+
79
+ class HealthCheckResponse(BaseModel):
80
+ status: str
81
+ server_stats: ServerStats
82
+ unhealthy_connections: List[dict]
83
+ timestamp: str
84
+
85
  # --- FastAPI Lifecycle Events (Startup and Shutdown) ---
86
 
87
  @app.on_event("startup")
 
181
  return CommandResponse(success=True, message="Reboot command sent successfully.")
182
  raise HTTPException(status_code=404, detail="Device not connected or command failed.")
183
 
184
+ @app.get("/api/server/stats", response_model=ServerStats)
185
+ async def get_server_stats():
186
+ """Get comprehensive server statistics."""
187
+ return isup_server.get_server_stats()
188
+
189
+ @app.get("/api/server/health", response_model=HealthCheckResponse)
190
+ async def get_server_health():
191
+ """Get detailed server health information."""
192
+ return await isup_server.health_check()
193
+
194
+ @app.get("/api/connections/details", response_model=List[ConnectionDetail])
195
+ async def get_connection_details():
196
+ """Get detailed information about all active connections."""
197
+ return isup_server.get_connection_details()
198
+
199
+ @app.get("/api/debug/connection-attempts")
200
+ async def get_connection_attempts():
201
+ """Get all connection attempts for debugging."""
202
+ from isup5_server import connection_attempts
203
+ return {"connection_attempts": connection_attempts}
204
+
205
+ @app.get("/api/debug/raw-requests")
206
+ async def get_raw_requests():
207
+ """Get all raw ISUP requests for debugging."""
208
+ from isup5_server import raw_requests
209
+ return {"raw_requests": raw_requests}
210
+
211
+ @app.get("/api/debug/registration-attempts")
212
+ async def get_registration_attempts():
213
+ """Get all device registration attempts for debugging."""
214
+ from isup5_server import registration_attempts
215
+ return {"registration_attempts": registration_attempts}
216
+
217
  # --- Error Handlers for API Robustness ---
218
 
219
  @app.exception_handler(404)
docs/.DS_Store CHANGED
Binary files a/docs/.DS_Store and b/docs/.DS_Store differ
 
docs/DEVICE_REGISTRATION_PROCESS.md ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hikvision Device Registration Process
2
+
3
+ Based on the ISUP SDK documentation, here's how Hikvision devices should register with your server:
4
+
5
+ ## Registration Flow Overview
6
+
7
+ According to the documentation, the device registration follows this sequence:
8
+
9
+ 1. **Device connects** to your ISUP server (TCP port 7660)
10
+ 2. **Device sends REGISTER_REQ** (0x01) with device information
11
+ 3. **Server responds** with REGISTER_RSP (0x81) - success/failure
12
+ 4. **Authentication phase** (if required):
13
+ - Device sends AUTH_REQ (0x03) with credentials
14
+ - Server responds with AUTH_RSP (0x83)
15
+ 5. **Session key exchange** (for ISUP 5.0):
16
+ - Device sends SESSIONKEY_REQ (0x04)
17
+ - Server responds with SESSIONKEY_RSP (0x84)
18
+ 6. **Heartbeat maintenance**:
19
+ - Device sends periodic HEARTBEAT_REQ (0x02)
20
+ - Server responds with HEARTBEAT_RSP (0x82)
21
+
22
+ ## Device Configuration Requirements
23
+
24
+ ### On the Hikvision Device:
25
+
26
+ 1. **Enable ISUP Protocol**:
27
+ - Go to Configuration β†’ Network β†’ Advanced Settings β†’ Platform
28
+ - Select "ISUP" from platform access mode
29
+ - Check "Enable"
30
+
31
+ 2. **Set ISUP Version**:
32
+ - Choose "5.0" for ISUP 5.0 protocol
33
+ - This requires setting an ISUP key (8-32 characters)
34
+
35
+ 3. **Configure Server Settings**:
36
+ - **Server IP**: Your server's IP address
37
+ - **Port**: 7660 (your ISUP server port)
38
+ - **Device ID**: Unique identifier for the device
39
+ - **ISUP Key**: Authentication key (for ISUP 5.0)
40
+
41
+ ### Example Device Settings:
42
+ ```
43
+ ISUP Version: 5.0
44
+ Server IP: your-server-ip
45
+ Port: 7660
46
+ Device ID: 255
47
+ ISUP Key: hikvision123
48
+ ```
49
+
50
+ ## Registration Message Format
51
+
52
+ ### REGISTER_REQ (0x01) Structure:
53
+ ```
54
+ ISUP Header (20 bytes):
55
+ - Version: 0x50 (ISUP 5.0)
56
+ - Message Type: 0x01 (REGISTER_REQ)
57
+ - Sequence: 2 bytes
58
+ - Device ID Length: 1 byte
59
+ - Device ID: 32 bytes (padded)
60
+ - Data Length: 2 bytes
61
+ - Reserved: 2 bytes
62
+
63
+ Registration Data:
64
+ - Serial Number
65
+ - Device Type
66
+ - Firmware Version
67
+ - MAC Address
68
+ - Capabilities
69
+ - Other device-specific information
70
+ ```
71
+
72
+ ## Troubleshooting Connection Issues
73
+
74
+ ### 1. Check Network Connectivity
75
+ ```bash
76
+ # Test if device can reach your server
77
+ ping your-server-ip
78
+
79
+ # Test if port is accessible
80
+ telnet your-server-ip 7660
81
+ ```
82
+
83
+ ### 2. Verify Server Configuration
84
+ - Ensure ISUP server is running on port 7660
85
+ - Check firewall settings
86
+ - Verify server logs for connection attempts
87
+
88
+ ### 3. Device Configuration Checklist
89
+ - [ ] ISUP protocol enabled
90
+ - [ ] Correct server IP and port
91
+ - [ ] Valid device ID set
92
+ - [ ] ISUP key configured (for v5.0)
93
+ - [ ] Network connectivity working
94
+
95
+ ### 4. Common Issues
96
+
97
+ **Device not connecting:**
98
+ - Check network connectivity
99
+ - Verify server IP/port settings
100
+ - Ensure ISUP is enabled on device
101
+
102
+ **Connection established but no registration:**
103
+ - Check ISUP version compatibility
104
+ - Verify device ID format
105
+ - Check authentication credentials
106
+
107
+ **Registration fails:**
108
+ - Verify device is in authorized devices list
109
+ - Check ISUP key matches
110
+ - Review server logs for error details
111
+
112
+ ## Debug Information
113
+
114
+ Your enhanced server now logs:
115
+
116
+ 1. **Connection Attempts**: All TCP connections to port 7660
117
+ 2. **Registration Attempts**: Device registration requests with details
118
+ 3. **Raw ISUP Messages**: All protocol messages with hex data
119
+
120
+ Access the debug information at: `http://your-server/debug`
121
+
122
+ ## Expected Device Behavior
123
+
124
+ When properly configured, a Hikvision device should:
125
+
126
+ 1. **Establish TCP connection** to your server
127
+ 2. **Send registration request** within seconds of connection
128
+ 3. **Maintain heartbeat** every 30-60 seconds
129
+ 4. **Send events** (access control, alarms) as they occur
130
+ 5. **Respond to commands** sent from server
131
+
132
+ ## Next Steps
133
+
134
+ 1. **Configure your device** with the correct ISUP settings
135
+ 2. **Monitor the Debug tab** to see if connection attempts are being made
136
+ 3. **Check registration attempts** to see if device is sending proper data
137
+ 4. **Review raw messages** to understand what the device is actually sending
138
+
139
+ If you see connection attempts but no registration, the device may be:
140
+ - Using a different ISUP version
141
+ - Sending malformed registration data
142
+ - Using different authentication method
143
+
144
+ The debug logging will help identify exactly what's happening!
docs/dev/.DS_Store CHANGED
Binary files a/docs/dev/.DS_Store and b/docs/dev/.DS_Store differ
 
isup5_server.py CHANGED
@@ -132,50 +132,92 @@ class ISUP5Connection:
132
  self.session_key = None
133
  self.ehome_key = None
134
  self.last_heartbeat = datetime.now()
 
135
  self.sequence_counter = 0
136
  self.status = DeviceStatus.CONNECTING
 
 
 
137
 
138
  def get_next_sequence(self) -> int:
139
  """Get next sequence number"""
140
  self.sequence_counter = (self.sequence_counter + 1) % 65536
141
  return self.sequence_counter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
  async def send_message(self, message: ISUPMessage):
144
  """Send ISUP message to device"""
145
  try:
 
 
 
146
  data = message.pack()
147
  self.writer.write(data)
148
  await self.writer.drain()
 
149
  logger.info(f"πŸ“€ Sent ISUP message type {message.header.message_type:02X} to {self.device_id}")
150
  except Exception as e:
 
 
151
  logger.error(f"Failed to send message to {self.device_id}: {e}")
152
-
 
153
  async def receive_message(self) -> Optional[ISUPMessage]:
154
  """Receive ISUP message from device"""
155
  try:
156
  # Read header first
157
  header_data = await self.reader.readexactly(ISUP_HEADER_SIZE)
158
-
159
  message = ISUPMessage()
160
  if not message.header.unpack(header_data):
 
 
161
  logger.error(f"Failed to unpack header from {self.address}")
162
  return None
163
-
164
  # Read data if present
165
  if message.header.data_length > 0:
166
  if message.header.data_length > ISUP_MAX_PACKET_SIZE:
167
- logger.error(f"Message too large: {message.header.data_length}")
 
 
168
  return None
169
-
170
  message.data = await self.reader.readexactly(message.header.data_length)
171
-
 
172
  logger.info(f"πŸ“₯ Received ISUP message type {message.header.message_type:02X} from {self.device_id or self.address}")
173
  return message
174
-
175
  except asyncio.IncompleteReadError:
176
  logger.info(f"Connection closed by {self.address}")
177
  return None
178
  except Exception as e:
 
 
179
  logger.error(f"Error receiving message from {self.address}: {e}")
180
  return None
181
 
@@ -213,57 +255,174 @@ session_keys: Dict[str, str] = {} # device_id -> session_key
213
  events: List[dict] = []
214
  attendance_logs: List[dict] = []
215
 
 
 
 
 
 
216
  class ISUP5Server:
217
  """ISUP 5.0 Binary Protocol Server"""
218
-
219
- def __init__(self, host='0.0.0.0', port=7660):
220
  self.host = host
221
  self.port = port
 
222
  self.server = None
223
-
 
 
224
  async def start(self):
225
  """Start ISUP 5.0 server"""
226
- self.server = await asyncio.start_server(
227
- self.handle_client,
228
- self.host,
229
- self.port
230
- )
231
-
232
- logger.info(f"πŸš€ ISUP 5.0 Server started on {self.host}:{self.port}")
233
- logger.info(f"πŸ“‹ Authorized devices: {len(AUTHORIZED_DEVICES)}")
234
-
235
- async with self.server:
236
- await self.server.serve_forever()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
 
238
  async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
239
  """Handle new client connection"""
240
  address = writer.get_extra_info('peername')
241
- logger.info(f"πŸ”— New ISUP connection from {address}")
242
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
243
  connection = ISUP5Connection(reader, writer, address)
244
-
245
  try:
246
- while True:
247
- message = await connection.receive_message()
248
- if message is None:
249
- break
250
-
251
- await self.process_message(connection, message)
252
-
 
 
 
253
  except Exception as e:
254
  logger.error(f"Error handling client {address}: {e}")
255
  finally:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  if connection.device_id:
257
  active_connections.pop(connection.device_id, None)
258
  logger.info(f"πŸ“΄ Device {connection.device_id} disconnected")
259
-
260
- writer.close()
261
- await writer.wait_closed()
 
 
 
 
 
 
262
 
263
  async def process_message(self, connection: ISUP5Connection, message: ISUPMessage):
264
  """Process incoming ISUP 5.0 message"""
265
  msg_type = message.header.message_type
266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  if msg_type == ISUPMessageType.REGISTER_REQ.value:
268
  await self.handle_register_request(connection, message)
269
  elif msg_type == ISUPMessageType.AUTH_REQ.value:
@@ -279,23 +438,86 @@ class ISUP5Server:
279
  else:
280
  logger.warning(f"Unknown message type: {msg_type:02X}")
281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  async def handle_register_request(self, connection: ISUP5Connection, message: ISUPMessage):
283
  """Handle device registration request (ISUP 5.0)"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  try:
285
  # Parse registration data
286
  if len(message.data) < 64: # Minimum registration data size
 
 
287
  await self.send_register_response(connection, False, "Invalid registration data")
288
  return
289
 
290
  # Extract device info from binary data
291
  device_info = self.parse_registration_data(message.data)
292
  if not device_info:
 
 
293
  await self.send_register_response(connection, False, "Failed to parse registration")
294
  return
295
 
296
  serial_number = device_info.get('serial_number')
297
  device_id = device_info.get('device_id')
298
 
 
 
 
 
299
  # Validate device
300
  if serial_number not in AUTHORIZED_DEVICES:
301
  logger.warning(f"❌ Unauthorized device: {serial_number}")
@@ -727,6 +949,49 @@ class ISUP5Server:
727
  """Get recent attendance records"""
728
  return attendance_logs[-limit:] if attendance_logs else []
729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
730
  # Command types for device control
731
  class DeviceCommands:
732
  OPEN_DOOR = 0x01
 
132
  self.session_key = None
133
  self.ehome_key = None
134
  self.last_heartbeat = datetime.now()
135
+ self.connected_at = datetime.now()
136
  self.sequence_counter = 0
137
  self.status = DeviceStatus.CONNECTING
138
+ self.message_count = 0
139
+ self.error_count = 0
140
+ self.last_error = None
141
 
142
  def get_next_sequence(self) -> int:
143
  """Get next sequence number"""
144
  self.sequence_counter = (self.sequence_counter + 1) % 65536
145
  return self.sequence_counter
146
+
147
+ def is_healthy(self) -> bool:
148
+ """Check if connection is healthy"""
149
+ now = datetime.now()
150
+ heartbeat_timeout = (now - self.last_heartbeat).total_seconds() > 120 # 2 minutes
151
+ error_rate_high = self.error_count > 10 and self.message_count > 0 and (self.error_count / self.message_count) > 0.1
152
+
153
+ return not (heartbeat_timeout or error_rate_high)
154
+
155
+ def get_connection_info(self) -> dict:
156
+ """Get connection information"""
157
+ now = datetime.now()
158
+ return {
159
+ "device_id": self.device_id,
160
+ "address": f"{self.address[0]}:{self.address[1]}",
161
+ "status": self.status.value,
162
+ "authenticated": self.authenticated,
163
+ "connected_duration": str(now - self.connected_at),
164
+ "last_heartbeat": str(now - self.last_heartbeat),
165
+ "message_count": self.message_count,
166
+ "error_count": self.error_count,
167
+ "last_error": self.last_error,
168
+ "is_healthy": self.is_healthy()
169
+ }
170
 
171
  async def send_message(self, message: ISUPMessage):
172
  """Send ISUP message to device"""
173
  try:
174
+ if self.writer.is_closing():
175
+ raise ConnectionError("Connection is closing")
176
+
177
  data = message.pack()
178
  self.writer.write(data)
179
  await self.writer.drain()
180
+ self.message_count += 1
181
  logger.info(f"πŸ“€ Sent ISUP message type {message.header.message_type:02X} to {self.device_id}")
182
  except Exception as e:
183
+ self.error_count += 1
184
+ self.last_error = str(e)
185
  logger.error(f"Failed to send message to {self.device_id}: {e}")
186
+ raise
187
+
188
  async def receive_message(self) -> Optional[ISUPMessage]:
189
  """Receive ISUP message from device"""
190
  try:
191
  # Read header first
192
  header_data = await self.reader.readexactly(ISUP_HEADER_SIZE)
193
+
194
  message = ISUPMessage()
195
  if not message.header.unpack(header_data):
196
+ self.error_count += 1
197
+ self.last_error = "Failed to unpack header"
198
  logger.error(f"Failed to unpack header from {self.address}")
199
  return None
200
+
201
  # Read data if present
202
  if message.header.data_length > 0:
203
  if message.header.data_length > ISUP_MAX_PACKET_SIZE:
204
+ self.error_count += 1
205
+ self.last_error = f"Message too large: {message.header.data_length}"
206
+ logger.error(self.last_error)
207
  return None
208
+
209
  message.data = await self.reader.readexactly(message.header.data_length)
210
+
211
+ self.message_count += 1
212
  logger.info(f"πŸ“₯ Received ISUP message type {message.header.message_type:02X} from {self.device_id or self.address}")
213
  return message
214
+
215
  except asyncio.IncompleteReadError:
216
  logger.info(f"Connection closed by {self.address}")
217
  return None
218
  except Exception as e:
219
+ self.error_count += 1
220
+ self.last_error = str(e)
221
  logger.error(f"Error receiving message from {self.address}: {e}")
222
  return None
223
 
 
255
  events: List[dict] = []
256
  attendance_logs: List[dict] = []
257
 
258
+ # Connection and request logging
259
+ connection_attempts: List[dict] = []
260
+ raw_requests: List[dict] = []
261
+ registration_attempts: List[dict] = []
262
+
263
  class ISUP5Server:
264
  """ISUP 5.0 Binary Protocol Server"""
265
+
266
+ def __init__(self, host='0.0.0.0', port=7660, max_connections=100):
267
  self.host = host
268
  self.port = port
269
+ self.max_connections = max_connections
270
  self.server = None
271
+ self.running = False
272
+ self.connection_count = 0
273
+
274
  async def start(self):
275
  """Start ISUP 5.0 server"""
276
+ if self.running:
277
+ logger.warning("Server is already running")
278
+ return
279
+
280
+ try:
281
+ self.server = await asyncio.start_server(
282
+ self.handle_client,
283
+ self.host,
284
+ self.port,
285
+ limit=self.max_connections,
286
+ reuse_address=True,
287
+ reuse_port=True
288
+ )
289
+
290
+ self.running = True
291
+ logger.info(f"πŸš€ ISUP 5.0 Server started on {self.host}:{self.port}")
292
+ logger.info(f"πŸ“‹ Authorized devices: {len(AUTHORIZED_DEVICES)}")
293
+ logger.info(f"πŸ”§ Max connections: {self.max_connections}")
294
+
295
+ async with self.server:
296
+ await self.server.serve_forever()
297
+
298
+ except Exception as e:
299
+ logger.error(f"Failed to start server: {e}")
300
+ self.running = False
301
+ raise
302
+
303
+ async def stop(self):
304
+ """Stop the server gracefully"""
305
+ if not self.running or not self.server:
306
+ return
307
+
308
+ logger.info("πŸ›‘ Stopping ISUP 5.0 Server...")
309
+ self.running = False
310
+
311
+ # Close all active connections
312
+ for device_id, connection in list(active_connections.items()):
313
+ try:
314
+ connection.writer.close()
315
+ await connection.writer.wait_closed()
316
+ except Exception as e:
317
+ logger.error(f"Error closing connection for {device_id}: {e}")
318
+
319
+ active_connections.clear()
320
+
321
+ # Close the server
322
+ self.server.close()
323
+ await self.server.wait_closed()
324
+ logger.info("βœ… Server stopped successfully")
325
 
326
  async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
327
  """Handle new client connection"""
328
  address = writer.get_extra_info('peername')
329
+
330
+ # Log all connection attempts
331
+ connection_attempt = {
332
+ "timestamp": datetime.now().isoformat(),
333
+ "source_ip": address[0],
334
+ "source_port": address[1],
335
+ "status": "attempting",
336
+ "user_agent": None,
337
+ "connection_type": "TCP"
338
+ }
339
+ connection_attempts.append(connection_attempt)
340
+
341
+ # Keep only last 100 connection attempts
342
+ if len(connection_attempts) > 100:
343
+ connection_attempts.pop(0)
344
+
345
+ # Check connection limits
346
+ if self.connection_count >= self.max_connections:
347
+ logger.warning(f"🚫 Connection limit reached, rejecting {address}")
348
+ connection_attempt["status"] = "rejected_limit"
349
+ writer.close()
350
+ await writer.wait_closed()
351
+ return
352
+
353
+ self.connection_count += 1
354
+ logger.info(f"πŸ”— New ISUP connection from {address} (total: {self.connection_count})")
355
+ connection_attempt["status"] = "accepted"
356
+
357
  connection = ISUP5Connection(reader, writer, address)
358
+
359
  try:
360
+ # Set connection timeout
361
+ await asyncio.wait_for(
362
+ self._handle_connection_messages(connection),
363
+ timeout=300.0 # 5 minutes timeout for inactive connections
364
+ )
365
+
366
+ except asyncio.TimeoutError:
367
+ logger.warning(f"⏰ Connection timeout for {address}")
368
+ except ConnectionResetError:
369
+ logger.info(f"πŸ”Œ Connection reset by {address}")
370
  except Exception as e:
371
  logger.error(f"Error handling client {address}: {e}")
372
  finally:
373
+ await self._cleanup_connection(connection)
374
+
375
+ async def _handle_connection_messages(self, connection: ISUP5Connection):
376
+ """Handle messages for a connection"""
377
+ while self.running:
378
+ message = await connection.receive_message()
379
+ if message is None:
380
+ break
381
+
382
+ await self.process_message(connection, message)
383
+
384
+ async def _cleanup_connection(self, connection: ISUP5Connection):
385
+ """Clean up connection resources"""
386
+ try:
387
  if connection.device_id:
388
  active_connections.pop(connection.device_id, None)
389
  logger.info(f"πŸ“΄ Device {connection.device_id} disconnected")
390
+
391
+ if not connection.writer.is_closing():
392
+ connection.writer.close()
393
+ await connection.writer.wait_closed()
394
+
395
+ except Exception as e:
396
+ logger.error(f"Error during connection cleanup: {e}")
397
+ finally:
398
+ self.connection_count = max(0, self.connection_count - 1)
399
 
400
  async def process_message(self, connection: ISUP5Connection, message: ISUPMessage):
401
  """Process incoming ISUP 5.0 message"""
402
  msg_type = message.header.message_type
403
 
404
+ # Log all raw requests for debugging
405
+ raw_request = {
406
+ "timestamp": datetime.now().isoformat(),
407
+ "source_ip": connection.address[0],
408
+ "source_port": connection.address[1],
409
+ "device_id": connection.device_id or "unknown",
410
+ "message_type": f"0x{msg_type:02X}",
411
+ "message_type_name": self._get_message_type_name(msg_type),
412
+ "sequence": message.header.sequence,
413
+ "data_length": message.header.data_length,
414
+ "raw_data_hex": message.data.hex() if message.data else "",
415
+ "raw_data_preview": self._get_data_preview(message.data),
416
+ "connection_status": connection.status.value if connection.status else "unknown"
417
+ }
418
+ raw_requests.append(raw_request)
419
+
420
+ # Keep only last 200 raw requests
421
+ if len(raw_requests) > 200:
422
+ raw_requests.pop(0)
423
+
424
+ logger.info(f"πŸ“¨ Processing {raw_request['message_type_name']} from {connection.device_id or connection.address}")
425
+
426
  if msg_type == ISUPMessageType.REGISTER_REQ.value:
427
  await self.handle_register_request(connection, message)
428
  elif msg_type == ISUPMessageType.AUTH_REQ.value:
 
438
  else:
439
  logger.warning(f"Unknown message type: {msg_type:02X}")
440
 
441
+ def _get_message_type_name(self, message_type: int) -> str:
442
+ """Get human-readable message type name"""
443
+ type_names = {
444
+ 0x01: "REGISTER_REQ",
445
+ 0x81: "REGISTER_RSP",
446
+ 0x02: "HEARTBEAT_REQ",
447
+ 0x82: "HEARTBEAT_RSP",
448
+ 0x03: "AUTH_REQ",
449
+ 0x83: "AUTH_RSP",
450
+ 0x04: "SESSIONKEY_REQ",
451
+ 0x84: "SESSIONKEY_RSP",
452
+ 0x05: "EVENT_REPORT",
453
+ 0x85: "EVENT_ACK",
454
+ 0x06: "COMMAND_REQ",
455
+ 0x86: "COMMAND_RSP",
456
+ 0x07: "BINARY_DATA",
457
+ 0x87: "BINARY_ACK"
458
+ }
459
+ return type_names.get(message_type, f"UNKNOWN_0x{message_type:02X}")
460
+
461
+ def _get_data_preview(self, data: bytes) -> str:
462
+ """Get a preview of the data for logging"""
463
+ if not data:
464
+ return ""
465
+
466
+ # Try to decode as UTF-8 for text preview
467
+ try:
468
+ text_preview = data[:100].decode('utf-8', errors='ignore')
469
+ return f"Text: {text_preview[:50]}{'...' if len(text_preview) > 50 else ''}"
470
+ except:
471
+ pass
472
+
473
+ # Show hex preview for binary data
474
+ hex_preview = data[:20].hex()
475
+ return f"Hex: {hex_preview}{'...' if len(data) > 20 else ''}"
476
+
477
  async def handle_register_request(self, connection: ISUP5Connection, message: ISUPMessage):
478
  """Handle device registration request (ISUP 5.0)"""
479
+
480
+ # Log registration attempt
481
+ registration_attempt = {
482
+ "timestamp": datetime.now().isoformat(),
483
+ "source_ip": connection.address[0],
484
+ "source_port": connection.address[1],
485
+ "data_length": len(message.data),
486
+ "raw_data_hex": message.data.hex() if message.data else "",
487
+ "status": "attempting",
488
+ "device_id": None,
489
+ "serial_number": None,
490
+ "error_message": None
491
+ }
492
+ registration_attempts.append(registration_attempt)
493
+
494
+ # Keep only last 50 registration attempts
495
+ if len(registration_attempts) > 50:
496
+ registration_attempts.pop(0)
497
+
498
  try:
499
  # Parse registration data
500
  if len(message.data) < 64: # Minimum registration data size
501
+ registration_attempt["status"] = "failed"
502
+ registration_attempt["error_message"] = "Invalid registration data - too short"
503
  await self.send_register_response(connection, False, "Invalid registration data")
504
  return
505
 
506
  # Extract device info from binary data
507
  device_info = self.parse_registration_data(message.data)
508
  if not device_info:
509
+ registration_attempt["status"] = "failed"
510
+ registration_attempt["error_message"] = "Failed to parse registration data"
511
  await self.send_register_response(connection, False, "Failed to parse registration")
512
  return
513
 
514
  serial_number = device_info.get('serial_number')
515
  device_id = device_info.get('device_id')
516
 
517
+ # Update registration attempt with parsed info
518
+ registration_attempt["device_id"] = device_id
519
+ registration_attempt["serial_number"] = serial_number
520
+
521
  # Validate device
522
  if serial_number not in AUTHORIZED_DEVICES:
523
  logger.warning(f"❌ Unauthorized device: {serial_number}")
 
949
  """Get recent attendance records"""
950
  return attendance_logs[-limit:] if attendance_logs else []
951
 
952
+ def get_server_stats(self) -> dict:
953
+ """Get server statistics"""
954
+ healthy_connections = sum(1 for conn in active_connections.values() if conn.is_healthy())
955
+ total_messages = sum(conn.message_count for conn in active_connections.values())
956
+ total_errors = sum(conn.error_count for conn in active_connections.values())
957
+
958
+ return {
959
+ "server_running": self.running,
960
+ "total_connections": self.connection_count,
961
+ "active_devices": len(active_connections),
962
+ "healthy_connections": healthy_connections,
963
+ "authorized_devices": len(AUTHORIZED_DEVICES),
964
+ "total_messages_processed": total_messages,
965
+ "total_errors": total_errors,
966
+ "error_rate": (total_errors / total_messages * 100) if total_messages > 0 else 0,
967
+ "recent_events": len(events),
968
+ "attendance_records": len(attendance_logs)
969
+ }
970
+
971
+ def get_connection_details(self) -> List[dict]:
972
+ """Get detailed information about all connections"""
973
+ return [conn.get_connection_info() for conn in active_connections.values()]
974
+
975
+ async def health_check(self) -> dict:
976
+ """Perform server health check"""
977
+ stats = self.get_server_stats()
978
+ unhealthy_connections = []
979
+
980
+ for device_id, conn in active_connections.items():
981
+ if not conn.is_healthy():
982
+ unhealthy_connections.append({
983
+ "device_id": device_id,
984
+ "address": f"{conn.address[0]}:{conn.address[1]}",
985
+ "issue": "heartbeat_timeout" if (datetime.now() - conn.last_heartbeat).total_seconds() > 120 else "high_error_rate"
986
+ })
987
+
988
+ return {
989
+ "status": "healthy" if len(unhealthy_connections) == 0 else "degraded",
990
+ "server_stats": stats,
991
+ "unhealthy_connections": unhealthy_connections,
992
+ "timestamp": datetime.now().isoformat()
993
+ }
994
+
995
  # Command types for device control
996
  class DeviceCommands:
997
  OPEN_DOOR = 0x01
templates/dashboard.html CHANGED
@@ -306,6 +306,23 @@
306
  line-height: 1.5;
307
  }
308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  .alert {
310
  padding: 16px;
311
  border-radius: 8px;
@@ -725,6 +742,7 @@
725
  <button class="nav-tab" onclick="showTab('events')">Events</button>
726
  <button class="nav-tab" onclick="showTab('attendance')">Attendance</button>
727
  <button class="nav-tab" onclick="showTab('config')">Configuration</button>
 
728
  <button class="nav-tab" onclick="showTab('api')">API</button>
729
  </div>
730
 
@@ -792,6 +810,62 @@
792
  </div>
793
  </div>
794
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
795
  <div class="section">
796
  <div class="section-title">Quick Actions</div>
797
  <div class="btn-group">
@@ -902,6 +976,24 @@
902
  </div>
903
  </div>
904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
905
  <div class="section">
906
  <div class="grid grid-2">
907
  <div class="card">
@@ -1152,7 +1244,80 @@
1152
  </div>
1153
  </div>
1154
  </div>
1155
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1156
  <!-- API Docs Tab -->
1157
  <div id="api" class="tab-content">
1158
  <div class="section">
@@ -1437,8 +1602,231 @@
1437
  }
1438
  }
1439
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1440
  function refreshData() {
1441
- location.reload();
 
 
 
1442
  }
1443
 
1444
  function showNotification(message, type = 'info') {
@@ -1469,11 +1857,30 @@
1469
 
1470
  // Initialize on page load
1471
  document.addEventListener('DOMContentLoaded', function() {
 
 
 
1472
  // Auto-refresh connections if on that tab
1473
  if (window.location.hash === '#connections') {
1474
  showTab('connections');
1475
  refreshConnections();
 
 
 
 
1476
  }
 
 
 
 
 
 
 
 
 
 
 
 
1477
  });
1478
  </script>
1479
  </body>
 
306
  line-height: 1.5;
307
  }
308
 
309
+ .debug-item {
310
+ transition: all 0.2s ease;
311
+ }
312
+
313
+ .debug-item:hover {
314
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
315
+ }
316
+
317
+ .badge {
318
+ background: #3182ce;
319
+ color: white;
320
+ padding: 2px 8px;
321
+ border-radius: 12px;
322
+ font-size: 12px;
323
+ font-weight: 500;
324
+ }
325
+
326
  .alert {
327
  padding: 16px;
328
  border-radius: 8px;
 
742
  <button class="nav-tab" onclick="showTab('events')">Events</button>
743
  <button class="nav-tab" onclick="showTab('attendance')">Attendance</button>
744
  <button class="nav-tab" onclick="showTab('config')">Configuration</button>
745
+ <button class="nav-tab" onclick="showTab('debug')">Debug</button>
746
  <button class="nav-tab" onclick="showTab('api')">API</button>
747
  </div>
748
 
 
810
  </div>
811
  </div>
812
 
813
+ <div class="section">
814
+ <div class="section-title">Server Health & Performance</div>
815
+ <div class="grid grid-3">
816
+ <div class="card">
817
+ <div class="card-header">
818
+ <h3 class="card-title">Connection Statistics</h3>
819
+ </div>
820
+ <div class="card-body">
821
+ <div class="stat-grid">
822
+ <div class="stat-item">
823
+ <div class="stat-value" id="total-connections">-</div>
824
+ <div class="stat-label">Total Connections</div>
825
+ </div>
826
+ <div class="stat-item">
827
+ <div class="stat-value" id="healthy-connections">-</div>
828
+ <div class="stat-label">Healthy</div>
829
+ </div>
830
+ </div>
831
+ </div>
832
+ </div>
833
+
834
+ <div class="card">
835
+ <div class="card-header">
836
+ <h3 class="card-title">Message Processing</h3>
837
+ </div>
838
+ <div class="card-body">
839
+ <div class="stat-grid">
840
+ <div class="stat-item">
841
+ <div class="stat-value" id="total-messages">-</div>
842
+ <div class="stat-label">Messages Processed</div>
843
+ </div>
844
+ <div class="stat-item">
845
+ <div class="stat-value" id="error-rate">-</div>
846
+ <div class="stat-label">Error Rate (%)</div>
847
+ </div>
848
+ </div>
849
+ </div>
850
+ </div>
851
+
852
+ <div class="card">
853
+ <div class="card-header">
854
+ <h3 class="card-title">System Health</h3>
855
+ </div>
856
+ <div class="card-body">
857
+ <div class="stat-item">
858
+ <div class="status-indicator" id="health-status">
859
+ <span class="status-dot"></span>
860
+ <span id="health-text">Checking...</span>
861
+ </div>
862
+ <div class="stat-label">Overall Status</div>
863
+ </div>
864
+ </div>
865
+ </div>
866
+ </div>
867
+ </div>
868
+
869
  <div class="section">
870
  <div class="section-title">Quick Actions</div>
871
  <div class="btn-group">
 
976
  </div>
977
  </div>
978
 
979
+ <div class="section">
980
+ <div class="section-title">Connection Health Details</div>
981
+ <div class="card">
982
+ <div class="card-header">
983
+ <h3 class="card-title">Detailed Connection Information</h3>
984
+ <button class="btn btn-sm" onclick="refreshConnectionDetails()">Refresh Details</button>
985
+ </div>
986
+ <div class="card-body">
987
+ <div id="connection-details">
988
+ <div class="empty-state">
989
+ <div class="empty-state-icon">πŸ“Š</div>
990
+ <div class="empty-state-title">Loading connection details...</div>
991
+ </div>
992
+ </div>
993
+ </div>
994
+ </div>
995
+ </div>
996
+
997
  <div class="section">
998
  <div class="grid grid-2">
999
  <div class="card">
 
1244
  </div>
1245
  </div>
1246
  </div>
1247
+
1248
+ <!-- Debug Tab -->
1249
+ <div id="debug" class="tab-content">
1250
+ <div class="section">
1251
+ <div class="section-title">Connection Debug Information</div>
1252
+ <div class="btn-group" style="margin-bottom: 20px;">
1253
+ <button class="btn btn-primary" onclick="refreshDebugData()">Refresh Debug Data</button>
1254
+ <button class="btn" onclick="clearDebugData()">Clear All Logs</button>
1255
+ </div>
1256
+
1257
+ <div class="grid grid-1">
1258
+ <div class="card">
1259
+ <div class="card-header">
1260
+ <h3 class="card-title">Connection Attempts</h3>
1261
+ <span class="badge" id="connection-attempts-count">0</span>
1262
+ </div>
1263
+ <div class="card-body">
1264
+ <div id="connection-attempts-list">
1265
+ <div class="empty-state">
1266
+ <div class="empty-state-icon">πŸ”</div>
1267
+ <div class="empty-state-title">No connection attempts logged</div>
1268
+ <div class="empty-state-description">
1269
+ Connection attempts will appear here when devices try to connect.
1270
+ </div>
1271
+ </div>
1272
+ </div>
1273
+ </div>
1274
+ </div>
1275
+ </div>
1276
+ </div>
1277
+
1278
+ <div class="section">
1279
+ <div class="section-title">Registration Attempts</div>
1280
+ <div class="card">
1281
+ <div class="card-header">
1282
+ <h3 class="card-title">Device Registration Attempts</h3>
1283
+ <span class="badge" id="registration-attempts-count">0</span>
1284
+ </div>
1285
+ <div class="card-body">
1286
+ <div id="registration-attempts-list">
1287
+ <div class="empty-state">
1288
+ <div class="empty-state-icon">πŸ“</div>
1289
+ <div class="empty-state-title">No registration attempts logged</div>
1290
+ <div class="empty-state-description">
1291
+ Device registration attempts will appear here.
1292
+ </div>
1293
+ </div>
1294
+ </div>
1295
+ </div>
1296
+ </div>
1297
+ </div>
1298
+
1299
+ <div class="section">
1300
+ <div class="section-title">Raw ISUP Messages</div>
1301
+ <div class="card">
1302
+ <div class="card-header">
1303
+ <h3 class="card-title">All ISUP Protocol Messages</h3>
1304
+ <span class="badge" id="raw-requests-count">0</span>
1305
+ </div>
1306
+ <div class="card-body">
1307
+ <div id="raw-requests-list">
1308
+ <div class="empty-state">
1309
+ <div class="empty-state-icon">πŸ“‘</div>
1310
+ <div class="empty-state-title">No ISUP messages logged</div>
1311
+ <div class="empty-state-description">
1312
+ Raw ISUP protocol messages will appear here.
1313
+ </div>
1314
+ </div>
1315
+ </div>
1316
+ </div>
1317
+ </div>
1318
+ </div>
1319
+ </div>
1320
+
1321
  <!-- API Docs Tab -->
1322
  <div id="api" class="tab-content">
1323
  <div class="section">
 
1602
  }
1603
  }
1604
 
1605
+ async function refreshServerStats() {
1606
+ try {
1607
+ const response = await fetch('/api/server/stats');
1608
+ const stats = await response.json();
1609
+
1610
+ // Update dashboard statistics
1611
+ document.getElementById('total-connections').textContent = stats.total_connections;
1612
+ document.getElementById('healthy-connections').textContent = stats.healthy_connections;
1613
+ document.getElementById('total-messages').textContent = stats.total_messages_processed.toLocaleString();
1614
+ document.getElementById('error-rate').textContent = stats.error_rate.toFixed(2);
1615
+
1616
+ // Update health status
1617
+ const healthResponse = await fetch('/api/server/health');
1618
+ const health = await healthResponse.json();
1619
+
1620
+ const healthStatus = document.getElementById('health-status');
1621
+ const healthText = document.getElementById('health-text');
1622
+
1623
+ healthStatus.className = `status-indicator status-${health.status === 'healthy' ? 'online' : 'warning'}`;
1624
+ healthText.textContent = health.status === 'healthy' ? 'Healthy' : 'Degraded';
1625
+
1626
+ } catch (error) {
1627
+ console.error('Error refreshing server stats:', error);
1628
+ showNotification('Error refreshing server statistics', 'error');
1629
+ }
1630
+ }
1631
+
1632
+ async function refreshConnectionDetails() {
1633
+ try {
1634
+ const response = await fetch('/api/connections/details');
1635
+ const connections = await response.json();
1636
+
1637
+ const detailsContainer = document.getElementById('connection-details');
1638
+
1639
+ if (connections.length === 0) {
1640
+ detailsContainer.innerHTML = `
1641
+ <div class="empty-state">
1642
+ <div class="empty-state-icon">πŸ“Š</div>
1643
+ <div class="empty-state-title">No active connections</div>
1644
+ </div>
1645
+ `;
1646
+ return;
1647
+ }
1648
+
1649
+ detailsContainer.innerHTML = connections.map(conn => `
1650
+ <div class="connection-detail-card" style="border: 1px solid #e1e5e9; border-radius: 8px; padding: 16px; margin-bottom: 16px;">
1651
+ <div style="display: flex; justify-content: between; align-items: center; margin-bottom: 12px;">
1652
+ <h4 style="margin: 0; color: #1a202c;">${conn.device_id || 'Unknown Device'}</h4>
1653
+ <div class="status-indicator status-${conn.is_healthy ? 'online' : 'warning'}">
1654
+ <span class="status-dot"></span>
1655
+ ${conn.is_healthy ? 'Healthy' : 'Issues'}
1656
+ </div>
1657
+ </div>
1658
+ <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px;">
1659
+ <div>
1660
+ <strong>Address:</strong> ${conn.address}<br>
1661
+ <strong>Status:</strong> ${conn.status}<br>
1662
+ <strong>Authenticated:</strong> ${conn.authenticated ? 'Yes' : 'No'}
1663
+ </div>
1664
+ <div>
1665
+ <strong>Connected:</strong> ${conn.connected_duration}<br>
1666
+ <strong>Last Heartbeat:</strong> ${conn.last_heartbeat}<br>
1667
+ <strong>Messages:</strong> ${conn.message_count}
1668
+ </div>
1669
+ <div>
1670
+ <strong>Errors:</strong> ${conn.error_count}<br>
1671
+ ${conn.last_error ? `<strong>Last Error:</strong> ${conn.last_error}` : ''}
1672
+ </div>
1673
+ </div>
1674
+ </div>
1675
+ `).join('');
1676
+
1677
+ } catch (error) {
1678
+ console.error('Error refreshing connection details:', error);
1679
+ showNotification('Error refreshing connection details', 'error');
1680
+ }
1681
+ }
1682
+
1683
+ async function refreshDebugData() {
1684
+ try {
1685
+ // Fetch connection attempts
1686
+ const connectionAttemptsResponse = await fetch('/api/debug/connection-attempts');
1687
+ const connectionAttemptsData = await connectionAttemptsResponse.json();
1688
+ displayConnectionAttempts(connectionAttemptsData.connection_attempts);
1689
+
1690
+ // Fetch registration attempts
1691
+ const registrationAttemptsResponse = await fetch('/api/debug/registration-attempts');
1692
+ const registrationAttemptsData = await registrationAttemptsResponse.json();
1693
+ displayRegistrationAttempts(registrationAttemptsData.registration_attempts);
1694
+
1695
+ // Fetch raw requests
1696
+ const rawRequestsResponse = await fetch('/api/debug/raw-requests');
1697
+ const rawRequestsData = await rawRequestsResponse.json();
1698
+ displayRawRequests(rawRequestsData.raw_requests);
1699
+
1700
+ } catch (error) {
1701
+ console.error('Error refreshing debug data:', error);
1702
+ showNotification('Error refreshing debug data', 'error');
1703
+ }
1704
+ }
1705
+
1706
+ function displayConnectionAttempts(attempts) {
1707
+ const container = document.getElementById('connection-attempts-list');
1708
+ const countBadge = document.getElementById('connection-attempts-count');
1709
+
1710
+ countBadge.textContent = attempts.length;
1711
+
1712
+ if (attempts.length === 0) {
1713
+ container.innerHTML = `
1714
+ <div class="empty-state">
1715
+ <div class="empty-state-icon">πŸ”</div>
1716
+ <div class="empty-state-title">No connection attempts logged</div>
1717
+ </div>
1718
+ `;
1719
+ return;
1720
+ }
1721
+
1722
+ container.innerHTML = attempts.slice(-20).reverse().map(attempt => `
1723
+ <div class="debug-item" style="border: 1px solid #e1e5e9; border-radius: 8px; padding: 12px; margin-bottom: 8px;">
1724
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
1725
+ <strong>${attempt.source_ip}:${attempt.source_port}</strong>
1726
+ <div class="status-indicator status-${attempt.status === 'accepted' ? 'online' : 'warning'}">
1727
+ <span class="status-dot"></span>
1728
+ ${attempt.status}
1729
+ </div>
1730
+ </div>
1731
+ <div style="font-size: 12px; color: #666;">
1732
+ <div>Time: ${new Date(attempt.timestamp).toLocaleString()}</div>
1733
+ <div>Type: ${attempt.connection_type}</div>
1734
+ </div>
1735
+ </div>
1736
+ `).join('');
1737
+ }
1738
+
1739
+ function displayRegistrationAttempts(attempts) {
1740
+ const container = document.getElementById('registration-attempts-list');
1741
+ const countBadge = document.getElementById('registration-attempts-count');
1742
+
1743
+ countBadge.textContent = attempts.length;
1744
+
1745
+ if (attempts.length === 0) {
1746
+ container.innerHTML = `
1747
+ <div class="empty-state">
1748
+ <div class="empty-state-icon">πŸ“</div>
1749
+ <div class="empty-state-title">No registration attempts logged</div>
1750
+ </div>
1751
+ `;
1752
+ return;
1753
+ }
1754
+
1755
+ container.innerHTML = attempts.slice(-10).reverse().map(attempt => `
1756
+ <div class="debug-item" style="border: 1px solid #e1e5e9; border-radius: 8px; padding: 12px; margin-bottom: 8px;">
1757
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
1758
+ <strong>${attempt.device_id || 'Unknown Device'}</strong>
1759
+ <div class="status-indicator status-${attempt.status === 'success' ? 'online' : 'warning'}">
1760
+ <span class="status-dot"></span>
1761
+ ${attempt.status}
1762
+ </div>
1763
+ </div>
1764
+ <div style="font-size: 12px; color: #666;">
1765
+ <div>Time: ${new Date(attempt.timestamp).toLocaleString()}</div>
1766
+ <div>From: ${attempt.source_ip}:${attempt.source_port}</div>
1767
+ <div>Serial: ${attempt.serial_number || 'N/A'}</div>
1768
+ <div>Data Length: ${attempt.data_length} bytes</div>
1769
+ ${attempt.error_message ? `<div style="color: #e53e3e;">Error: ${attempt.error_message}</div>` : ''}
1770
+ </div>
1771
+ <details style="margin-top: 8px;">
1772
+ <summary style="cursor: pointer; font-size: 12px;">Raw Data</summary>
1773
+ <pre style="font-size: 10px; background: #f7fafc; padding: 8px; border-radius: 4px; overflow-x: auto; margin-top: 4px;">${attempt.raw_data_hex}</pre>
1774
+ </details>
1775
+ </div>
1776
+ `).join('');
1777
+ }
1778
+
1779
+ function displayRawRequests(requests) {
1780
+ const container = document.getElementById('raw-requests-list');
1781
+ const countBadge = document.getElementById('raw-requests-count');
1782
+
1783
+ countBadge.textContent = requests.length;
1784
+
1785
+ if (requests.length === 0) {
1786
+ container.innerHTML = `
1787
+ <div class="empty-state">
1788
+ <div class="empty-state-icon">πŸ“‘</div>
1789
+ <div class="empty-state-title">No ISUP messages logged</div>
1790
+ </div>
1791
+ `;
1792
+ return;
1793
+ }
1794
+
1795
+ container.innerHTML = requests.slice(-15).reverse().map(request => `
1796
+ <div class="debug-item" style="border: 1px solid #e1e5e9; border-radius: 8px; padding: 12px; margin-bottom: 8px;">
1797
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
1798
+ <strong>${request.message_type_name}</strong>
1799
+ <span style="font-family: monospace; background: #f7fafc; padding: 2px 6px; border-radius: 4px;">${request.message_type}</span>
1800
+ </div>
1801
+ <div style="font-size: 12px; color: #666;">
1802
+ <div>Time: ${new Date(request.timestamp).toLocaleString()}</div>
1803
+ <div>From: ${request.source_ip}:${request.source_port} (${request.device_id})</div>
1804
+ <div>Sequence: ${request.sequence}, Length: ${request.data_length} bytes</div>
1805
+ <div>Status: ${request.connection_status}</div>
1806
+ </div>
1807
+ <details style="margin-top: 8px;">
1808
+ <summary style="cursor: pointer; font-size: 12px;">Message Data</summary>
1809
+ <div style="margin-top: 4px;">
1810
+ <div style="font-size: 11px; margin-bottom: 4px;">${request.raw_data_preview}</div>
1811
+ <pre style="font-size: 10px; background: #f7fafc; padding: 8px; border-radius: 4px; overflow-x: auto;">${request.raw_data_hex}</pre>
1812
+ </div>
1813
+ </details>
1814
+ </div>
1815
+ `).join('');
1816
+ }
1817
+
1818
+ function clearDebugData() {
1819
+ if (confirm('Are you sure you want to clear all debug logs? This action cannot be undone.')) {
1820
+ // Note: This would require a server endpoint to actually clear the data
1821
+ showNotification('Debug data clearing is not implemented yet', 'info');
1822
+ }
1823
+ }
1824
+
1825
  function refreshData() {
1826
+ // Enhanced refresh that updates all dashboard data
1827
+ refreshServerStats();
1828
+ refreshConnections();
1829
+ refreshConnectionDetails();
1830
  }
1831
 
1832
  function showNotification(message, type = 'info') {
 
1857
 
1858
  // Initialize on page load
1859
  document.addEventListener('DOMContentLoaded', function() {
1860
+ // Initialize dashboard with server stats
1861
+ refreshServerStats();
1862
+
1863
  // Auto-refresh connections if on that tab
1864
  if (window.location.hash === '#connections') {
1865
  showTab('connections');
1866
  refreshConnections();
1867
+ refreshConnectionDetails();
1868
+ } else if (window.location.hash === '#debug') {
1869
+ showTab('debug');
1870
+ refreshDebugData();
1871
  }
1872
+
1873
+ // Set up periodic refresh for dashboard stats (every 30 seconds)
1874
+ setInterval(() => {
1875
+ const activeTab = document.querySelector('.tab-content.active');
1876
+ if (activeTab && activeTab.id === 'dashboard') {
1877
+ refreshServerStats();
1878
+ } else if (activeTab && activeTab.id === 'connections') {
1879
+ refreshConnectionDetails();
1880
+ } else if (activeTab && activeTab.id === 'debug') {
1881
+ refreshDebugData();
1882
+ }
1883
+ }, 30000);
1884
  });
1885
  </script>
1886
  </body>
test/test_connection_logging.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Test Connection Logging
4
+ Simple test to verify that connection attempts and requests are being logged properly
5
+ """
6
+
7
+ import asyncio
8
+ import socket
9
+ import struct
10
+ import sys
11
+ import os
12
+
13
+ # Add parent directory to path
14
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
15
+
16
+ async def test_basic_connection():
17
+ """Test basic TCP connection to see if it gets logged"""
18
+ print("πŸ§ͺ Testing basic TCP connection logging...")
19
+
20
+ try:
21
+ # Try to connect to the ISUP server
22
+ reader, writer = await asyncio.open_connection('localhost', 7660)
23
+ print("βœ… Connected to ISUP server")
24
+
25
+ # Send some invalid data to test logging
26
+ writer.write(b"HELLO_WORLD_INVALID_ISUP_DATA")
27
+ await writer.drain()
28
+ print("πŸ“€ Sent invalid data")
29
+
30
+ # Wait a moment
31
+ await asyncio.sleep(1)
32
+
33
+ # Close connection
34
+ writer.close()
35
+ await writer.wait_closed()
36
+ print("πŸ“΄ Connection closed")
37
+
38
+ except Exception as e:
39
+ print(f"❌ Connection test failed: {e}")
40
+
41
+ async def test_isup_header():
42
+ """Test sending a malformed ISUP header"""
43
+ print("\nπŸ§ͺ Testing ISUP header logging...")
44
+
45
+ try:
46
+ reader, writer = await asyncio.open_connection('localhost', 7660)
47
+ print("βœ… Connected to ISUP server")
48
+
49
+ # Create a malformed ISUP header (wrong size)
50
+ fake_header = struct.pack('>BBHB32sHH',
51
+ 0x50, # ISUP version 5.0
52
+ 0x01, # REGISTER_REQ
53
+ 0x0001, # sequence
54
+ 10, # device_id_len
55
+ b"TEST_DEVICE".ljust(32, b'\x00'), # device_id
56
+ 0, # data_length
57
+ 0 # reserved
58
+ )
59
+
60
+ writer.write(fake_header)
61
+ await writer.drain()
62
+ print("πŸ“€ Sent malformed ISUP header")
63
+
64
+ # Wait a moment
65
+ await asyncio.sleep(1)
66
+
67
+ writer.close()
68
+ await writer.wait_closed()
69
+ print("πŸ“΄ Connection closed")
70
+
71
+ except Exception as e:
72
+ print(f"❌ ISUP header test failed: {e}")
73
+
74
+ async def test_registration_attempt():
75
+ """Test sending a registration request"""
76
+ print("\nπŸ§ͺ Testing registration attempt logging...")
77
+
78
+ try:
79
+ reader, writer = await asyncio.open_connection('localhost', 7660)
80
+ print("βœ… Connected to ISUP server")
81
+
82
+ # Create a proper ISUP registration request
83
+ device_id = "TEST_DEVICE_123"
84
+ registration_data = b"FAKE_REGISTRATION_DATA_FOR_TESTING" + b"\x00" * 50
85
+
86
+ header = struct.pack('>BBHB32sHH',
87
+ 0x50, # ISUP version 5.0
88
+ 0x01, # REGISTER_REQ
89
+ 0x0001, # sequence
90
+ len(device_id), # device_id_len
91
+ device_id.encode('utf-8').ljust(32, b'\x00'), # device_id
92
+ len(registration_data), # data_length
93
+ 0 # reserved
94
+ )
95
+
96
+ # Send header + data
97
+ writer.write(header + registration_data)
98
+ await writer.drain()
99
+ print("πŸ“€ Sent registration request")
100
+
101
+ # Try to read response
102
+ try:
103
+ response_header = await asyncio.wait_for(reader.read(20), timeout=2.0)
104
+ if response_header:
105
+ print(f"πŸ“₯ Received response: {len(response_header)} bytes")
106
+ else:
107
+ print("πŸ“₯ No response received")
108
+ except asyncio.TimeoutError:
109
+ print("⏰ Response timeout")
110
+
111
+ writer.close()
112
+ await writer.wait_closed()
113
+ print("πŸ“΄ Connection closed")
114
+
115
+ except Exception as e:
116
+ print(f"❌ Registration test failed: {e}")
117
+
118
+ async def test_multiple_connections():
119
+ """Test multiple simultaneous connections"""
120
+ print("\nπŸ§ͺ Testing multiple connection logging...")
121
+
122
+ tasks = []
123
+ for i in range(3):
124
+ tasks.append(test_single_connection(i))
125
+
126
+ await asyncio.gather(*tasks, return_exceptions=True)
127
+ print("βœ… Multiple connection test completed")
128
+
129
+ async def test_single_connection(connection_id):
130
+ """Single connection for multiple connection test"""
131
+ try:
132
+ reader, writer = await asyncio.open_connection('localhost', 7660)
133
+ print(f"βœ… Connection {connection_id} established")
134
+
135
+ # Send some data
136
+ writer.write(f"CONNECTION_{connection_id}_TEST_DATA".encode())
137
+ await writer.drain()
138
+
139
+ await asyncio.sleep(0.5)
140
+
141
+ writer.close()
142
+ await writer.wait_closed()
143
+ print(f"πŸ“΄ Connection {connection_id} closed")
144
+
145
+ except Exception as e:
146
+ print(f"❌ Connection {connection_id} failed: {e}")
147
+
148
+ def test_raw_socket():
149
+ """Test raw socket connection"""
150
+ print("\nπŸ§ͺ Testing raw socket connection...")
151
+
152
+ try:
153
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
154
+ sock.settimeout(5.0)
155
+
156
+ print("πŸ”— Attempting raw socket connection...")
157
+ sock.connect(('localhost', 7660))
158
+ print("βœ… Raw socket connected")
159
+
160
+ # Send some raw data
161
+ sock.send(b"RAW_SOCKET_TEST_DATA_123")
162
+ print("πŸ“€ Sent raw data")
163
+
164
+ sock.close()
165
+ print("πŸ“΄ Raw socket closed")
166
+
167
+ except Exception as e:
168
+ print(f"❌ Raw socket test failed: {e}")
169
+
170
+ async def main():
171
+ """Run all connection tests"""
172
+ print("πŸš€ Starting Connection Logging Tests")
173
+ print("=" * 50)
174
+
175
+ # Test basic connection
176
+ await test_basic_connection()
177
+
178
+ # Test ISUP header
179
+ await test_isup_header()
180
+
181
+ # Test registration attempt
182
+ await test_registration_attempt()
183
+
184
+ # Test multiple connections
185
+ await test_multiple_connections()
186
+
187
+ # Test raw socket
188
+ test_raw_socket()
189
+
190
+ print("\n" + "=" * 50)
191
+ print("🏁 All connection tests completed!")
192
+ print("\nπŸ’‘ Check the Debug tab in the dashboard to see logged connections:")
193
+ print(" http://localhost:7860/#debug")
194
+
195
+ if __name__ == "__main__":
196
+ asyncio.run(main())
test/test_tcp_server_improvements.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ TCP Server Improvements Test Suite
4
+ Tests the enhanced ISUP 5.0 TCP server functionality
5
+ """
6
+
7
+ import asyncio
8
+ import sys
9
+ import os
10
+ import time
11
+ import json
12
+ from datetime import datetime
13
+
14
+ # Add parent directory to path
15
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
16
+
17
+ from isup5_server import ISUP5Server, active_connections
18
+ from test.isup5_device_simulator import ISUP5DeviceSimulator
19
+
20
+ class TCPServerTester:
21
+ """Test suite for TCP server improvements"""
22
+
23
+ def __init__(self):
24
+ self.server = ISUP5Server(host='localhost', port=7661, max_connections=5)
25
+ self.test_results = []
26
+
27
+ async def run_all_tests(self):
28
+ """Run all test scenarios"""
29
+ print("πŸ§ͺ Starting TCP Server Improvement Tests")
30
+ print("=" * 50)
31
+
32
+ # Start server in background
33
+ server_task = asyncio.create_task(self.server.start())
34
+ await asyncio.sleep(1) # Give server time to start
35
+
36
+ try:
37
+ await self.test_basic_connection()
38
+ await self.test_connection_limits()
39
+ await self.test_connection_health_monitoring()
40
+ await self.test_error_handling()
41
+ await self.test_server_statistics()
42
+ await self.test_graceful_shutdown()
43
+
44
+ finally:
45
+ # Stop server
46
+ await self.server.stop()
47
+ server_task.cancel()
48
+ try:
49
+ await server_task
50
+ except asyncio.CancelledError:
51
+ pass
52
+
53
+ self.print_test_summary()
54
+
55
+ async def test_basic_connection(self):
56
+ """Test basic connection functionality"""
57
+ print("\nπŸ”— Testing Basic Connection...")
58
+
59
+ simulator = ISUP5DeviceSimulator(server_host='localhost', server_port=7661)
60
+
61
+ try:
62
+ # Test connection
63
+ connected = await simulator.connect()
64
+ self.assert_test(connected, "Device should connect successfully")
65
+
66
+ # Test registration
67
+ registered = await simulator.register()
68
+ self.assert_test(registered, "Device should register successfully")
69
+
70
+ # Test heartbeat
71
+ heartbeat_sent = await simulator.send_heartbeat()
72
+ self.assert_test(heartbeat_sent, "Heartbeat should be sent successfully")
73
+
74
+ await simulator.disconnect()
75
+ print("βœ… Basic connection test passed")
76
+
77
+ except Exception as e:
78
+ print(f"❌ Basic connection test failed: {e}")
79
+ self.test_results.append(("Basic Connection", False, str(e)))
80
+
81
+ async def test_connection_limits(self):
82
+ """Test connection limit enforcement"""
83
+ print("\n🚫 Testing Connection Limits...")
84
+
85
+ simulators = []
86
+
87
+ try:
88
+ # Create connections up to the limit
89
+ for i in range(self.server.max_connections):
90
+ sim = ISUP5DeviceSimulator(server_host='localhost', server_port=7661)
91
+ sim.device_id = f"test_device_{i}"
92
+ sim.serial_number = f"TEST{i:04d}"
93
+
94
+ connected = await sim.connect()
95
+ if connected:
96
+ simulators.append(sim)
97
+ await asyncio.sleep(0.1) # Small delay between connections
98
+
99
+ self.assert_test(
100
+ len(simulators) <= self.server.max_connections,
101
+ f"Should not exceed max connections ({self.server.max_connections})"
102
+ )
103
+
104
+ # Try to create one more connection (should be rejected)
105
+ extra_sim = ISUP5DeviceSimulator(server_host='localhost', server_port=7661)
106
+ extra_connected = await extra_sim.connect()
107
+
108
+ if extra_connected:
109
+ await extra_sim.disconnect()
110
+ print("⚠️ Extra connection was allowed (may indicate issue)")
111
+
112
+ print(f"βœ… Connection limits test passed ({len(simulators)} connections)")
113
+
114
+ except Exception as e:
115
+ print(f"❌ Connection limits test failed: {e}")
116
+ self.test_results.append(("Connection Limits", False, str(e)))
117
+
118
+ finally:
119
+ # Clean up all simulators
120
+ for sim in simulators:
121
+ try:
122
+ await sim.disconnect()
123
+ except:
124
+ pass
125
+
126
+ async def test_connection_health_monitoring(self):
127
+ """Test connection health monitoring"""
128
+ print("\nπŸ’“ Testing Connection Health Monitoring...")
129
+
130
+ simulator = ISUP5DeviceSimulator(server_host='localhost', server_port=7661)
131
+
132
+ try:
133
+ await simulator.connect()
134
+ await simulator.register()
135
+
136
+ # Get connection info
137
+ stats = self.server.get_server_stats()
138
+ self.assert_test(stats['active_devices'] >= 1, "Should have at least one active device")
139
+
140
+ # Test health check
141
+ health = await self.server.health_check()
142
+ self.assert_test(health['status'] in ['healthy', 'degraded'], "Health status should be valid")
143
+
144
+ # Get connection details
145
+ details = self.server.get_connection_details()
146
+ self.assert_test(len(details) >= 1, "Should have connection details")
147
+
148
+ if details:
149
+ conn_info = details[0]
150
+ required_fields = ['device_id', 'address', 'status', 'authenticated', 'is_healthy']
151
+ for field in required_fields:
152
+ self.assert_test(field in conn_info, f"Connection info should have {field}")
153
+
154
+ await simulator.disconnect()
155
+ print("βœ… Connection health monitoring test passed")
156
+
157
+ except Exception as e:
158
+ print(f"❌ Connection health monitoring test failed: {e}")
159
+ self.test_results.append(("Health Monitoring", False, str(e)))
160
+
161
+ async def test_error_handling(self):
162
+ """Test error handling and recovery"""
163
+ print("\nπŸ› οΈ Testing Error Handling...")
164
+
165
+ try:
166
+ # Test invalid connection (should be handled gracefully)
167
+ try:
168
+ reader, writer = await asyncio.open_connection('localhost', 7661)
169
+ # Send invalid data
170
+ writer.write(b"invalid_data_not_isup_protocol")
171
+ await writer.drain()
172
+ writer.close()
173
+ await writer.wait_closed()
174
+ except:
175
+ pass # Expected to fail
176
+
177
+ # Server should still be running
178
+ stats = self.server.get_server_stats()
179
+ self.assert_test(stats['server_running'], "Server should still be running after invalid connection")
180
+
181
+ print("βœ… Error handling test passed")
182
+
183
+ except Exception as e:
184
+ print(f"❌ Error handling test failed: {e}")
185
+ self.test_results.append(("Error Handling", False, str(e)))
186
+
187
+ async def test_server_statistics(self):
188
+ """Test server statistics functionality"""
189
+ print("\nπŸ“Š Testing Server Statistics...")
190
+
191
+ try:
192
+ stats = self.server.get_server_stats()
193
+
194
+ required_stats = [
195
+ 'server_running', 'total_connections', 'active_devices',
196
+ 'healthy_connections', 'authorized_devices', 'total_messages_processed',
197
+ 'total_errors', 'error_rate', 'recent_events', 'attendance_records'
198
+ ]
199
+
200
+ for stat in required_stats:
201
+ self.assert_test(stat in stats, f"Stats should include {stat}")
202
+
203
+ self.assert_test(isinstance(stats['error_rate'], (int, float)), "Error rate should be numeric")
204
+ self.assert_test(stats['error_rate'] >= 0, "Error rate should be non-negative")
205
+
206
+ print("βœ… Server statistics test passed")
207
+
208
+ except Exception as e:
209
+ print(f"❌ Server statistics test failed: {e}")
210
+ self.test_results.append(("Server Statistics", False, str(e)))
211
+
212
+ async def test_graceful_shutdown(self):
213
+ """Test graceful server shutdown"""
214
+ print("\nπŸ›‘ Testing Graceful Shutdown...")
215
+
216
+ try:
217
+ # Create a connection
218
+ simulator = ISUP5DeviceSimulator(server_host='localhost', server_port=7661)
219
+ await simulator.connect()
220
+ await simulator.register()
221
+
222
+ # Verify connection is active
223
+ stats_before = self.server.get_server_stats()
224
+ self.assert_test(stats_before['active_devices'] >= 1, "Should have active device before shutdown")
225
+
226
+ print("βœ… Graceful shutdown test setup completed")
227
+
228
+ except Exception as e:
229
+ print(f"❌ Graceful shutdown test failed: {e}")
230
+ self.test_results.append(("Graceful Shutdown", False, str(e)))
231
+
232
+ def assert_test(self, condition, message):
233
+ """Assert test condition and record result"""
234
+ if condition:
235
+ self.test_results.append((message, True, ""))
236
+ else:
237
+ self.test_results.append((message, False, "Assertion failed"))
238
+ print(f"❌ {message}")
239
+
240
+ def print_test_summary(self):
241
+ """Print test results summary"""
242
+ print("\n" + "=" * 50)
243
+ print("πŸ“‹ TEST RESULTS SUMMARY")
244
+ print("=" * 50)
245
+
246
+ passed = sum(1 for _, success, _ in self.test_results if success)
247
+ total = len(self.test_results)
248
+
249
+ print(f"Total Tests: {total}")
250
+ print(f"Passed: {passed}")
251
+ print(f"Failed: {total - passed}")
252
+ print(f"Success Rate: {(passed/total*100):.1f}%" if total > 0 else "N/A")
253
+
254
+ if total - passed > 0:
255
+ print("\n❌ Failed Tests:")
256
+ for test_name, success, error in self.test_results:
257
+ if not success:
258
+ print(f" - {test_name}: {error}")
259
+
260
+ print("\n" + "=" * 50)
261
+
262
+ async def main():
263
+ """Main test runner"""
264
+ tester = TCPServerTester()
265
+ await tester.run_all_tests()
266
+
267
+ if __name__ == "__main__":
268
+ asyncio.run(main())