54ac76a2 by huangyf2

new

1 parent 4696f3d6
1 2025-04-09 21:55:22,617 - websockets.server - INFO - server listening on [::1]:20111
2 2025-04-09 21:55:22,617 - websockets.server - INFO - server listening on 127.0.0.1:20111
3 2025-04-09 21:55:30,670 - websockets.server - INFO - connection open
4 2025-04-09 21:56:04,105 - websockets.server - INFO - server listening on [::1]:20111
5 2025-04-09 21:56:04,105 - websockets.server - INFO - server listening on 127.0.0.1:20111
6 2025-04-09 21:56:21,751 - websockets.server - INFO - connection open
...@@ -7,6 +7,8 @@ import json ...@@ -7,6 +7,8 @@ import json
7 import base64 7 import base64
8 import threading 8 import threading
9 from collections import defaultdict 9 from collections import defaultdict
10 import socket
11 import time
10 12
11 import platform 13 import platform
12 14
...@@ -36,6 +38,38 @@ async def log_message(direction, message): ...@@ -36,6 +38,38 @@ async def log_message(direction, message):
36 loop = asyncio.get_event_loop() 38 loop = asyncio.get_event_loop()
37 await loop.run_in_executor(None, log_message_sync, direction, message) 39 await loop.run_in_executor(None, log_message_sync, direction, message)
38 40
41 def is_port_in_use(port, host='localhost'):
42 """检查端口是否被占用"""
43 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
44 try:
45 s.bind((host, port))
46 return False
47 except socket.error:
48 return True
49
50 async def self_test(websocket):
51 """发送自检测试消息"""
52 test_message = json.dumps({
53 "jsonrpc": "2.0",
54 "method": "ping",
55 "params": {"timestamp": int(time.time())},
56 "id": "test"
57 })
58 await log_message("自测", test_message)
59 await websocket.send(test_message)
60
61 try:
62 # 等待响应,设置超时
63 response = await asyncio.wait_for(websocket.recv(), timeout=5.0)
64 await log_message("自测响应", response)
65 return True
66 except asyncio.TimeoutError:
67 await log_message("自测", "自测超时,未收到响应")
68 return False
69 except Exception as e:
70 await log_message("自测", f"自测异常: {str(e)}")
71 return False
72
39 class BLEClient: 73 class BLEClient:
40 def __init__(self): 74 def __init__(self):
41 self.target_device = None 75 self.target_device = None
...@@ -211,6 +245,16 @@ class BLEClient: ...@@ -211,6 +245,16 @@ class BLEClient:
211 await log_message("下发", response) 245 await log_message("下发", response)
212 await websocket.send(response) 246 await websocket.send(response)
213 247
248 elif method == "ping":
249 # 处理ping请求,返回pong响应
250 response = json.dumps({
251 "jsonrpc": "2.0",
252 "result": {"pong": True, "timestamp": int(time.time())},
253 "id": request_id
254 })
255 await log_message("下发", response)
256 await websocket.send(response)
257
214 except json.JSONDecodeError: 258 except json.JSONDecodeError:
215 error_msg = json.dumps({ 259 error_msg = json.dumps({
216 "jsonrpc": "2.0", 260 "jsonrpc": "2.0",
...@@ -262,14 +306,39 @@ class BLEClient: ...@@ -262,14 +306,39 @@ class BLEClient:
262 await websocket.send(response) 306 await websocket.send(response)
263 return callback 307 return callback
264 308
265 async def main(): 309 async def check_port_and_start_server(port=20111, host='localhost'):
266 async with websockets.serve( 310 """检查端口并启动服务器"""
311 if is_port_in_use(port, host):
312 print(f"错误: 端口 {port} 已被占用,无法启动服务")
313 return False
314
315 print(f"端口 {port} 可用,正在启动服务...")
316 server = await websockets.serve(
267 lambda websocket, path: BLEClient().handle_client(websocket, path), 317 lambda websocket, path: BLEClient().handle_client(websocket, path),
268 "localhost", 20111 318 host, port
269 ): 319 )
270 print("WebSocket服务已启动: ws://localhost:20111/scratch/ble") 320
321 print(f"WebSocket服务已启动: ws://{host}:{port}/scratch/ble")
271 print("日志文件路径: ./b.log") 322 print("日志文件路径: ./b.log")
272 await asyncio.Future() 323
324 # 执行自检测试
325 try:
326 async with websockets.connect(f"ws://{host}:{port}/scratch/ble") as websocket:
327 print("正在执行自检测试...")
328 test_result = await self_test(websocket)
329 if test_result:
330 print("自检测试成功: 服务正常运行")
331 else:
332 print("自检测试失败: 服务可能存在问题")
333 except Exception as e:
334 print(f"自检测试异常: {str(e)}")
335
336 return server
337
338 async def main():
339 server = await check_port_and_start_server()
340 if server:
341 await asyncio.Future() # 保持服务器运行
273 342
274 if __name__ == "__main__": 343 if __name__ == "__main__":
275 asyncio.run(main()) 344 asyncio.run(main())
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -3,14 +3,14 @@ ...@@ -3,14 +3,14 @@
3 3
4 a = Analysis( 4 a = Analysis(
5 ['s6.9.2.py'], 5 ['s6.9.2.py'],
6 pathex=[], 6 pathex=['C:\\Python\\Lib\\site-packages\\bleak\\backends'],
7 binaries=[], 7 binaries=[('C:\\Windows\\System32\\BluetoothApis.dll', '.')],
8 datas=[('data', 'data')], 8 datas=[('data', 'data')],
9 hiddenimports=['bleak.backends', 'asyncio'], 9 hiddenimports=['bleak.backends', 'bleak.backends.winrt', 'asyncio'],
10 hookspath=[], 10 hookspath=[],
11 hooksconfig={}, 11 hooksconfig={},
12 runtime_hooks=[], 12 runtime_hooks=[],
13 excludes=[], 13 excludes=['unnecessary_module'],
14 noarchive=False, 14 noarchive=False,
15 optimize=0, 15 optimize=0,
16 ) 16 )
......
Styling with Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!