add log
Showing
1 changed file
with
39 additions
and
3 deletions
| ... | @@ -39,7 +39,7 @@ _log_task = None | ... | @@ -39,7 +39,7 @@ _log_task = None |
| 39 | _log_dropped_count = 0 | 39 | _log_dropped_count = 0 |
| 40 | 40 | ||
| 41 | def log_message_sync(direction, message): | 41 | def log_message_sync(direction, message): |
| 42 | """同步日志记录函数""" | 42 | """同步日志记录函数(由异步日志系统调用)""" |
| 43 | try: | 43 | try: |
| 44 | log_entry = f"{direction}: {message}\n" | 44 | log_entry = f"{direction}: {message}\n" |
| 45 | print(log_entry, end='') # 控制台仍然输出 | 45 | print(log_entry, end='') # 控制台仍然输出 |
| ... | @@ -49,7 +49,7 @@ def log_message_sync(direction, message): | ... | @@ -49,7 +49,7 @@ def log_message_sync(direction, message): |
| 49 | log_entry = log_entry[:4000] + "... [truncated]\n" | 49 | log_entry = log_entry[:4000] + "... [truncated]\n" |
| 50 | 50 | ||
| 51 | with write_lock: | 51 | with write_lock: |
| 52 | with open('b.log', 'a', encoding='utf-8') as f: | 52 | with open('a.log', 'a', encoding='utf-8') as f: |
| 53 | f.write(log_entry) | 53 | f.write(log_entry) |
| 54 | except Exception: | 54 | except Exception: |
| 55 | pass # 日志失败不应影响主流程 | 55 | pass # 日志失败不应影响主流程 |
| ... | @@ -132,6 +132,8 @@ class BLEClient: | ... | @@ -132,6 +132,8 @@ class BLEClient: |
| 132 | 132 | ||
| 133 | def on_disconnect(self, client): | 133 | def on_disconnect(self, client): |
| 134 | print("BLE连接断开,关闭WebSocket") | 134 | print("BLE连接断开,关闭WebSocket") |
| 135 | # 异步记录日志 | ||
| 136 | asyncio.create_task(log_message("系统", "BLE连接断开,关闭WebSocket")) | ||
| 135 | # 设置关闭标志 | 137 | # 设置关闭标志 |
| 136 | self._shutdown = True | 138 | self._shutdown = True |
| 137 | # 在事件循环中关闭WebSocket | 139 | # 在事件循环中关闭WebSocket |
| ... | @@ -153,8 +155,10 @@ class BLEClient: | ... | @@ -153,8 +155,10 @@ class BLEClient: |
| 153 | # 使用1000状态码正常关闭 | 155 | # 使用1000状态码正常关闭 |
| 154 | await self.websocket.close(code=1000, reason="BLE connection closed") | 156 | await self.websocket.close(code=1000, reason="BLE connection closed") |
| 155 | print("WebSocket连接已关闭") | 157 | print("WebSocket连接已关闭") |
| 158 | await log_message("系统", "WebSocket连接已关闭") | ||
| 156 | except Exception as e: | 159 | except Exception as e: |
| 157 | print(f"关闭WebSocket时出错: {e}") | 160 | print(f"关闭WebSocket时出错: {e}") |
| 161 | await log_message("错误", f"关闭WebSocket时出错: {e}") | ||
| 158 | finally: | 162 | finally: |
| 159 | self.websocket = None | 163 | self.websocket = None |
| 160 | self._shutdown = True | 164 | self._shutdown = True |
| ... | @@ -171,6 +175,8 @@ class BLEClient: | ... | @@ -171,6 +175,8 @@ class BLEClient: |
| 171 | # 丢弃名字为空的设备 | 175 | # 丢弃名字为空的设备 |
| 172 | if not device_name or device_name.strip() == "": | 176 | if not device_name or device_name.strip() == "": |
| 173 | print(f"跳过名字为空的设备: {device.address}") | 177 | print(f"跳过名字为空的设备: {device.address}") |
| 178 | # 异步记录日志 | ||
| 179 | asyncio.create_task(log_message("扫描", f"跳过名字为空的设备: {device.address}")) | ||
| 174 | return None | 180 | return None |
| 175 | 181 | ||
| 176 | # 保存从广播包响应中获取的设备名称 | 182 | # 保存从广播包响应中获取的设备名称 |
| ... | @@ -194,6 +200,9 @@ class BLEClient: | ... | @@ -194,6 +200,9 @@ class BLEClient: |
| 194 | print(f"服务数据: {adv_data.service_data}") | 200 | print(f"服务数据: {adv_data.service_data}") |
| 195 | print(f"本地名称(local_name): {adv_data.local_name}") | 201 | print(f"本地名称(local_name): {adv_data.local_name}") |
| 196 | print(f"设备名称(device.name): {device.name if device.name else 'N/A'}") | 202 | print(f"设备名称(device.name): {device.name if device.name else 'N/A'}") |
| 203 | # 异步记录设备发现日志 | ||
| 204 | device_info = f"找到目标设备: {device_name} ({device.address}), RSSI: {device.rssi} dBm" | ||
| 205 | asyncio.create_task(log_message("扫描", device_info)) | ||
| 197 | # 发现设备后,尝试立即停止扫描 | 206 | # 发现设备后,尝试立即停止扫描 |
| 198 | try: | 207 | try: |
| 199 | if self._scanner is not None: | 208 | if self._scanner is not None: |
| ... | @@ -250,6 +259,7 @@ class BLEClient: | ... | @@ -250,6 +259,7 @@ class BLEClient: |
| 250 | self._scanner = BleakScanner(scanning_mode=scan_mode) | 259 | self._scanner = BleakScanner(scanning_mode=scan_mode) |
| 251 | self._scanner.register_detection_callback(self.detection_callback) | 260 | self._scanner.register_detection_callback(self.detection_callback) |
| 252 | print(f"开始第{phase_index}阶段扫描(模式: {scan_mode}, 时长: {duration}s)...") | 261 | print(f"开始第{phase_index}阶段扫描(模式: {scan_mode}, 时长: {duration}s)...") |
| 262 | await log_message("扫描", f"开始第{phase_index}阶段扫描(模式: {scan_mode}, 时长: {duration}s)") | ||
| 253 | try: | 263 | try: |
| 254 | await self._scanner.start() | 264 | await self._scanner.start() |
| 255 | # 轮询检查是否已找到,找到则提前停止 | 265 | # 轮询检查是否已找到,找到则提前停止 |
| ... | @@ -268,6 +278,7 @@ class BLEClient: | ... | @@ -268,6 +278,7 @@ class BLEClient: |
| 268 | break | 278 | break |
| 269 | else: | 279 | else: |
| 270 | print(f"第{phase_index}阶段未找到设备") | 280 | print(f"第{phase_index}阶段未找到设备") |
| 281 | await log_message("扫描", f"第{phase_index}阶段未找到设备") | ||
| 271 | 282 | ||
| 272 | if found: | 283 | if found: |
| 273 | device, adv_data = self.target_device | 284 | device, adv_data = self.target_device |
| ... | @@ -284,6 +295,7 @@ class BLEClient: | ... | @@ -284,6 +295,7 @@ class BLEClient: |
| 284 | # 补充检查:如果设备名称仍为空,使用设备地址作为名称 | 295 | # 补充检查:如果设备名称仍为空,使用设备地址作为名称 |
| 285 | if not device_name or device_name.strip() == "": | 296 | if not device_name or device_name.strip() == "": |
| 286 | print(f"警告: 设备名称为空,使用设备地址作为名称: {device.address}") | 297 | print(f"警告: 设备名称为空,使用设备地址作为名称: {device.address}") |
| 298 | await log_message("警告", f"设备名称为空,使用设备地址作为名称: {device.address}") | ||
| 287 | device_name = device.address # 使用设备地址作为备用名称 | 299 | device_name = device.address # 使用设备地址作为备用名称 |
| 288 | 300 | ||
| 289 | # 记录名称来源 | 301 | # 记录名称来源 |
| ... | @@ -291,6 +303,7 @@ class BLEClient: | ... | @@ -291,6 +303,7 @@ class BLEClient: |
| 291 | ("已保存的广播包名称" if self._device_name_from_advertisement else \ | 303 | ("已保存的广播包名称" if self._device_name_from_advertisement else \ |
| 292 | ("device.name" if device.name else "设备地址")) | 304 | ("device.name" if device.name else "设备地址")) |
| 293 | print(f"响应包中使用的设备名称来源: {name_source}") | 305 | print(f"响应包中使用的设备名称来源: {name_source}") |
| 306 | await log_message("系统", f"响应包中使用的设备名称来源: {name_source}") | ||
| 294 | 307 | ||
| 295 | discover_response = json.dumps({ | 308 | discover_response = json.dumps({ |
| 296 | "jsonrpc": "2.0", | 309 | "jsonrpc": "2.0", |
| ... | @@ -370,9 +383,11 @@ class BLEClient: | ... | @@ -370,9 +383,11 @@ class BLEClient: |
| 370 | if encoding == "base64": | 383 | if encoding == "base64": |
| 371 | message_bytes = base64.b64decode(message) | 384 | message_bytes = base64.b64decode(message) |
| 372 | print("write message_bytes",message_bytes) | 385 | print("write message_bytes",message_bytes) |
| 386 | await log_message("写入", f"Base64编码数据: {message_bytes.hex() if len(message_bytes) < 100 else message_bytes[:50].hex() + '...'}") | ||
| 373 | else: | 387 | else: |
| 374 | print("write message",message) | 388 | print("write message",message) |
| 375 | message_bytes = message.encode(encoding) | 389 | message_bytes = message.encode(encoding) |
| 390 | await log_message("写入", f"UTF-8消息: {message}") | ||
| 376 | 391 | ||
| 377 | await self.client.write_gatt_char(characteristic_id, message_bytes) | 392 | await self.client.write_gatt_char(characteristic_id, message_bytes) |
| 378 | response = json.dumps({ | 393 | response = json.dumps({ |
| ... | @@ -414,6 +429,7 @@ class BLEClient: | ... | @@ -414,6 +429,7 @@ class BLEClient: |
| 414 | timeout=10.0 | 429 | timeout=10.0 |
| 415 | ) | 430 | ) |
| 416 | print('read-data',data) | 431 | print('read-data',data) |
| 432 | await log_message("读取", f"特征 {characteristic_id}: {data.hex() if len(data) < 100 else data[:50].hex() + '...'}") | ||
| 417 | response = json.dumps({ | 433 | response = json.dumps({ |
| 418 | "jsonrpc": "2.0", | 434 | "jsonrpc": "2.0", |
| 419 | "result": { | 435 | "result": { |
| ... | @@ -528,6 +544,7 @@ class BLEClient: | ... | @@ -528,6 +544,7 @@ class BLEClient: |
| 528 | # 记录完整错误堆栈 | 544 | # 记录完整错误堆栈 |
| 529 | error_trace = traceback.format_exc() | 545 | error_trace = traceback.format_exc() |
| 530 | print(f"处理请求时出错: {error_trace}") | 546 | print(f"处理请求时出错: {error_trace}") |
| 547 | await log_message("错误", f"处理请求时出错: {error_trace}") | ||
| 531 | 548 | ||
| 532 | error_msg = json.dumps({ | 549 | error_msg = json.dumps({ |
| 533 | "jsonrpc": "2.0", | 550 | "jsonrpc": "2.0", |
| ... | @@ -543,6 +560,7 @@ class BLEClient: | ... | @@ -543,6 +560,7 @@ class BLEClient: |
| 543 | 560 | ||
| 544 | except websockets.exceptions.ConnectionClosed: | 561 | except websockets.exceptions.ConnectionClosed: |
| 545 | print("WebSocket连接关闭") | 562 | print("WebSocket连接关闭") |
| 563 | await log_message("系统", "WebSocket连接关闭") | ||
| 546 | finally: | 564 | finally: |
| 547 | # 清理BLE连接和通知 | 565 | # 清理BLE连接和通知 |
| 548 | self._shutdown = True | 566 | self._shutdown = True |
| ... | @@ -554,11 +572,13 @@ class BLEClient: | ... | @@ -554,11 +572,13 @@ class BLEClient: |
| 554 | await self.client.stop_notify(characteristic_id) | 572 | await self.client.stop_notify(characteristic_id) |
| 555 | except Exception as e: | 573 | except Exception as e: |
| 556 | print(f"停止通知失败 {characteristic_id}: {e}") | 574 | print(f"停止通知失败 {characteristic_id}: {e}") |
| 575 | await log_message("错误", f"停止通知失败 {characteristic_id}: {e}") | ||
| 557 | 576 | ||
| 558 | # 断开连接 | 577 | # 断开连接 |
| 559 | await self.client.disconnect() | 578 | await self.client.disconnect() |
| 560 | except Exception as e: | 579 | except Exception as e: |
| 561 | print(f"断开BLE连接失败: {e}") | 580 | print(f"断开BLE连接失败: {e}") |
| 581 | await log_message("错误", f"断开BLE连接失败: {e}") | ||
| 562 | finally: | 582 | finally: |
| 563 | self.client = None | 583 | self.client = None |
| 564 | self.target_device = None | 584 | self.target_device = None |
| ... | @@ -579,6 +599,8 @@ class BLEClient: | ... | @@ -579,6 +599,8 @@ class BLEClient: |
| 579 | # 解码当前数据用于比较 | 599 | # 解码当前数据用于比较 |
| 580 | current_message = base64.b64encode(data).decode('utf-8') | 600 | current_message = base64.b64encode(data).decode('utf-8') |
| 581 | print('notification_handler current_message',data) | 601 | print('notification_handler current_message',data) |
| 602 | # 异步记录通知日志(不阻塞通知处理) | ||
| 603 | asyncio.create_task(log_message("通知", f"特征 {characteristic_id}: {data.hex() if len(data) < 100 else data[:50].hex() + '...'}")) | ||
| 582 | 604 | ||
| 583 | # 过滤逻辑 - 只在0.5秒内且消息完全相同时跳过 | 605 | # 过滤逻辑 - 只在0.5秒内且消息完全相同时跳过 |
| 584 | if current_message == last_message and (current_time - last_time) < 0.5: | 606 | if current_message == last_message and (current_time - last_time) < 0.5: |
| ... | @@ -608,20 +630,29 @@ class BLEClient: | ... | @@ -608,20 +630,29 @@ class BLEClient: |
| 608 | await websocket.send(response) | 630 | await websocket.send(response) |
| 609 | except websockets.exceptions.ConnectionClosed: | 631 | except websockets.exceptions.ConnectionClosed: |
| 610 | print("WebSocket连接已关闭,停止发送通知") | 632 | print("WebSocket连接已关闭,停止发送通知") |
| 633 | await log_message("系统", "WebSocket连接已关闭,停止发送通知") | ||
| 611 | self._shutdown = True | 634 | self._shutdown = True |
| 612 | except Exception as e: | 635 | except Exception as e: |
| 613 | print(f"发送通知失败: {e}") | 636 | print(f"发送通知失败: {e}") |
| 637 | await log_message("错误", f"发送通知失败: {e}") | ||
| 614 | except Exception as e: | 638 | except Exception as e: |
| 615 | print(f"通知处理器出错: {e}") | 639 | print(f"通知处理器出错: {e}") |
| 640 | # 注意:这里不能使用 await,因为可能不在 async 上下文中 | ||
| 641 | try: | ||
| 642 | asyncio.create_task(log_message("错误", f"通知处理器出错: {e}")) | ||
| 643 | except Exception: | ||
| 644 | pass | ||
| 616 | return callback | 645 | return callback |
| 617 | 646 | ||
| 618 | async def check_port_and_start_server(port=20111, host='localhost'): | 647 | async def check_port_and_start_server(port=20111, host='localhost'): |
| 619 | """检查端口并启动服务器""" | 648 | """检查端口并启动服务器""" |
| 620 | if is_port_in_use(port, host): | 649 | if is_port_in_use(port, host): |
| 621 | print(f"错误: 端口 {port} 已被占用,无法启动服务") | 650 | print(f"错误: 端口 {port} 已被占用,无法启动服务") |
| 651 | await log_message("错误", f"端口 {port} 已被占用,无法启动服务") | ||
| 622 | return False | 652 | return False |
| 623 | 653 | ||
| 624 | print(f"端口 {port} 可用,正在启动服务...") | 654 | print(f"端口 {port} 可用,正在启动服务...") |
| 655 | await log_message("系统", f"端口 {port} 可用,正在启动服务") | ||
| 625 | server = await websockets.serve( | 656 | server = await websockets.serve( |
| 626 | lambda websocket, path: BLEClient().handle_client(websocket, path), | 657 | lambda websocket, path: BLEClient().handle_client(websocket, path), |
| 627 | host, port, | 658 | host, port, |
| ... | @@ -632,19 +663,24 @@ async def check_port_and_start_server(port=20111, host='localhost'): | ... | @@ -632,19 +663,24 @@ async def check_port_and_start_server(port=20111, host='localhost'): |
| 632 | ) | 663 | ) |
| 633 | 664 | ||
| 634 | print(f"WebSocket服务已启动: ws://{host}:{port}/scratch/ble") | 665 | print(f"WebSocket服务已启动: ws://{host}:{port}/scratch/ble") |
| 635 | print("日志文件路径: ./b.log") | 666 | print("日志文件路径: ./a.log") |
| 667 | await log_message("系统", f"WebSocket服务已启动: ws://{host}:{port}/scratch/ble") | ||
| 636 | 668 | ||
| 637 | # 执行自检测试 | 669 | # 执行自检测试 |
| 638 | try: | 670 | try: |
| 639 | async with websockets.connect(f"ws://{host}:{port}/scratch/ble") as websocket: | 671 | async with websockets.connect(f"ws://{host}:{port}/scratch/ble") as websocket: |
| 640 | print("正在执行自检测试...") | 672 | print("正在执行自检测试...") |
| 673 | await log_message("系统", "正在执行自检测试...") | ||
| 641 | test_result = await self_test(websocket) | 674 | test_result = await self_test(websocket) |
| 642 | if test_result: | 675 | if test_result: |
| 643 | print("自检测试成功: 服务正常运行") | 676 | print("自检测试成功: 服务正常运行") |
| 677 | await log_message("系统", "自检测试成功: 服务正常运行") | ||
| 644 | else: | 678 | else: |
| 645 | print("自检测试失败: 服务可能存在问题") | 679 | print("自检测试失败: 服务可能存在问题") |
| 680 | await log_message("警告", "自检测试失败: 服务可能存在问题") | ||
| 646 | except Exception as e: | 681 | except Exception as e: |
| 647 | print(f"自检测试异常: {str(e)}") | 682 | print(f"自检测试异常: {str(e)}") |
| 683 | await log_message("错误", f"自检测试异常: {str(e)}") | ||
| 648 | 684 | ||
| 649 | return server | 685 | return server |
| 650 | 686 | ... | ... |
-
Please register or sign in to post a comment