-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_websocket.py
More file actions
91 lines (68 loc) · 2.81 KB
/
test_websocket.py
File metadata and controls
91 lines (68 loc) · 2.81 KB
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
#!/usr/bin/env python3
"""
Simple WebSocket client to test the step detection API
"""
import asyncio
import json
import time
import websockets
async def test_websocket():
"""Test WebSocket connection"""
uri = "ws://localhost:8000/ws/realtime"
try:
print("🔌 Connecting to WebSocket...")
async with websockets.connect(uri) as websocket:
print("✅ Connected successfully!")
# Wait for welcome message
try:
welcome_msg = await asyncio.wait_for(websocket.recv(), timeout=5.0)
print(f"📨 Received: {welcome_msg}")
# Send a test sensor data
test_data = {
"accel_x": 0.1,
"accel_y": 0.2,
"accel_z": 9.8,
"gyro_x": 0.01,
"gyro_y": 0.02,
"gyro_z": 0.03,
}
print(f"📤 Sending test data: {test_data}")
await websocket.send(json.dumps(test_data))
# Wait for response
response = await asyncio.wait_for(websocket.recv(), timeout=5.0)
print(f"📨 Received response: {response}")
# Keep connection alive for a bit
print("⏱️ Keeping connection alive for 10 seconds...")
await asyncio.sleep(10)
print("✅ Test completed successfully!")
except asyncio.TimeoutError:
print("⏰ Timeout waiting for message")
except Exception as e:
print(f"❌ Error during communication: {e}")
except websockets.exceptions.ConnectionClosed as e:
print(f"🔌 Connection closed: {e}")
except Exception as e:
print(f"❌ Connection error: {e}")
async def test_websocket_with_user():
"""Test WebSocket connection with user ID"""
user_id = "test_user_123"
uri = f"ws://localhost:8000/ws/realtime/{user_id}"
try:
print(f"🔌 Connecting to WebSocket with user ID: {user_id}...")
async with websockets.connect(uri) as websocket:
print("✅ Connected successfully!")
# Wait for welcome message
welcome_msg = await asyncio.wait_for(websocket.recv(), timeout=5.0)
print(f"📨 Received: {welcome_msg}")
print("✅ User-based connection test completed!")
except Exception as e:
print(f"❌ User connection error: {e}")
if __name__ == "__main__":
print("🧪 Testing WebSocket connections...\n")
# Test regular connection
print("1️⃣ Testing regular WebSocket connection:")
asyncio.run(test_websocket())
print("\n" + "=" * 50 + "\n")
# Test user-based connection
print("2️⃣ Testing user-based WebSocket connection:")
asyncio.run(test_websocket_with_user())