Skip to content
Toggle navigation
Toggle navigation
This project
Loading...
Sign in
wenzhou
/
pythonserver
Go to a project
Toggle navigation
Toggle navigation pinning
Projects
Groups
Snippets
Help
Project
Activity
Repository
Pipelines
Graphs
Issues
0
Merge Requests
0
Wiki
Network
Create a new issue
Builds
Commits
Issue Boards
Files
Commits
Network
Compare
Branches
Tags
56902b59
authored
2025-11-05 18:04:06 +0800
by
huangyf2
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
add log
1 parent
fc75f31b
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
39 additions
and
3 deletions
s6.9.2.py
s6.9.2.py
View file @
56902b5
...
...
@@ -39,7 +39,7 @@ _log_task = None
_log_dropped_count
=
0
def
log_message_sync
(
direction
,
message
):
"""同步日志记录函数"""
"""同步日志记录函数
(由异步日志系统调用)
"""
try
:
log_entry
=
f
"{direction}: {message}
\n
"
print
(
log_entry
,
end
=
''
)
# 控制台仍然输出
...
...
@@ -49,7 +49,7 @@ def log_message_sync(direction, message):
log_entry
=
log_entry
[:
4000
]
+
"... [truncated]
\n
"
with
write_lock
:
with
open
(
'
b
.log'
,
'a'
,
encoding
=
'utf-8'
)
as
f
:
with
open
(
'
a
.log'
,
'a'
,
encoding
=
'utf-8'
)
as
f
:
f
.
write
(
log_entry
)
except
Exception
:
pass
# 日志失败不应影响主流程
...
...
@@ -132,6 +132,8 @@ class BLEClient:
def
on_disconnect
(
self
,
client
):
print
(
"BLE连接断开,关闭WebSocket"
)
# 异步记录日志
asyncio
.
create_task
(
log_message
(
"系统"
,
"BLE连接断开,关闭WebSocket"
))
# 设置关闭标志
self
.
_shutdown
=
True
# 在事件循环中关闭WebSocket
...
...
@@ -153,8 +155,10 @@ class BLEClient:
# 使用1000状态码正常关闭
await
self
.
websocket
.
close
(
code
=
1000
,
reason
=
"BLE connection closed"
)
print
(
"WebSocket连接已关闭"
)
await
log_message
(
"系统"
,
"WebSocket连接已关闭"
)
except
Exception
as
e
:
print
(
f
"关闭WebSocket时出错: {e}"
)
await
log_message
(
"错误"
,
f
"关闭WebSocket时出错: {e}"
)
finally
:
self
.
websocket
=
None
self
.
_shutdown
=
True
...
...
@@ -171,6 +175,8 @@ class BLEClient:
# 丢弃名字为空的设备
if
not
device_name
or
device_name
.
strip
()
==
""
:
print
(
f
"跳过名字为空的设备: {device.address}"
)
# 异步记录日志
asyncio
.
create_task
(
log_message
(
"扫描"
,
f
"跳过名字为空的设备: {device.address}"
))
return
None
# 保存从广播包响应中获取的设备名称
...
...
@@ -194,6 +200,9 @@ class BLEClient:
print
(
f
"服务数据: {adv_data.service_data}"
)
print
(
f
"本地名称(local_name): {adv_data.local_name}"
)
print
(
f
"设备名称(device.name): {device.name if device.name else 'N/A'}"
)
# 异步记录设备发现日志
device_info
=
f
"找到目标设备: {device_name} ({device.address}), RSSI: {device.rssi} dBm"
asyncio
.
create_task
(
log_message
(
"扫描"
,
device_info
))
# 发现设备后,尝试立即停止扫描
try
:
if
self
.
_scanner
is
not
None
:
...
...
@@ -250,6 +259,7 @@ class BLEClient:
self
.
_scanner
=
BleakScanner
(
scanning_mode
=
scan_mode
)
self
.
_scanner
.
register_detection_callback
(
self
.
detection_callback
)
print
(
f
"开始第{phase_index}阶段扫描(模式: {scan_mode}, 时长: {duration}s)..."
)
await
log_message
(
"扫描"
,
f
"开始第{phase_index}阶段扫描(模式: {scan_mode}, 时长: {duration}s)"
)
try
:
await
self
.
_scanner
.
start
()
# 轮询检查是否已找到,找到则提前停止
...
...
@@ -268,6 +278,7 @@ class BLEClient:
break
else
:
print
(
f
"第{phase_index}阶段未找到设备"
)
await
log_message
(
"扫描"
,
f
"第{phase_index}阶段未找到设备"
)
if
found
:
device
,
adv_data
=
self
.
target_device
...
...
@@ -284,6 +295,7 @@ class BLEClient:
# 补充检查:如果设备名称仍为空,使用设备地址作为名称
if
not
device_name
or
device_name
.
strip
()
==
""
:
print
(
f
"警告: 设备名称为空,使用设备地址作为名称: {device.address}"
)
await
log_message
(
"警告"
,
f
"设备名称为空,使用设备地址作为名称: {device.address}"
)
device_name
=
device
.
address
# 使用设备地址作为备用名称
# 记录名称来源
...
...
@@ -291,6 +303,7 @@ class BLEClient:
(
"已保存的广播包名称"
if
self
.
_device_name_from_advertisement
else
\
(
"device.name"
if
device
.
name
else
"设备地址"
))
print
(
f
"响应包中使用的设备名称来源: {name_source}"
)
await
log_message
(
"系统"
,
f
"响应包中使用的设备名称来源: {name_source}"
)
discover_response
=
json
.
dumps
({
"jsonrpc"
:
"2.0"
,
...
...
@@ -370,9 +383,11 @@ class BLEClient:
if
encoding
==
"base64"
:
message_bytes
=
base64
.
b64decode
(
message
)
print
(
"write message_bytes"
,
message_bytes
)
await
log_message
(
"写入"
,
f
"Base64编码数据: {message_bytes.hex() if len(message_bytes) < 100 else message_bytes[:50].hex() + '...'}"
)
else
:
print
(
"write message"
,
message
)
message_bytes
=
message
.
encode
(
encoding
)
await
log_message
(
"写入"
,
f
"UTF-8消息: {message}"
)
await
self
.
client
.
write_gatt_char
(
characteristic_id
,
message_bytes
)
response
=
json
.
dumps
({
...
...
@@ -414,6 +429,7 @@ class BLEClient:
timeout
=
10.0
)
print
(
'read-data'
,
data
)
await
log_message
(
"读取"
,
f
"特征 {characteristic_id}: {data.hex() if len(data) < 100 else data[:50].hex() + '...'}"
)
response
=
json
.
dumps
({
"jsonrpc"
:
"2.0"
,
"result"
:
{
...
...
@@ -528,6 +544,7 @@ class BLEClient:
# 记录完整错误堆栈
error_trace
=
traceback
.
format_exc
()
print
(
f
"处理请求时出错: {error_trace}"
)
await
log_message
(
"错误"
,
f
"处理请求时出错: {error_trace}"
)
error_msg
=
json
.
dumps
({
"jsonrpc"
:
"2.0"
,
...
...
@@ -543,6 +560,7 @@ class BLEClient:
except
websockets
.
exceptions
.
ConnectionClosed
:
print
(
"WebSocket连接关闭"
)
await
log_message
(
"系统"
,
"WebSocket连接关闭"
)
finally
:
# 清理BLE连接和通知
self
.
_shutdown
=
True
...
...
@@ -554,11 +572,13 @@ class BLEClient:
await
self
.
client
.
stop_notify
(
characteristic_id
)
except
Exception
as
e
:
print
(
f
"停止通知失败 {characteristic_id}: {e}"
)
await
log_message
(
"错误"
,
f
"停止通知失败 {characteristic_id}: {e}"
)
# 断开连接
await
self
.
client
.
disconnect
()
except
Exception
as
e
:
print
(
f
"断开BLE连接失败: {e}"
)
await
log_message
(
"错误"
,
f
"断开BLE连接失败: {e}"
)
finally
:
self
.
client
=
None
self
.
target_device
=
None
...
...
@@ -579,6 +599,8 @@ class BLEClient:
# 解码当前数据用于比较
current_message
=
base64
.
b64encode
(
data
)
.
decode
(
'utf-8'
)
print
(
'notification_handler current_message'
,
data
)
# 异步记录通知日志(不阻塞通知处理)
asyncio
.
create_task
(
log_message
(
"通知"
,
f
"特征 {characteristic_id}: {data.hex() if len(data) < 100 else data[:50].hex() + '...'}"
))
# 过滤逻辑 - 只在0.5秒内且消息完全相同时跳过
if
current_message
==
last_message
and
(
current_time
-
last_time
)
<
0.5
:
...
...
@@ -608,20 +630,29 @@ class BLEClient:
await
websocket
.
send
(
response
)
except
websockets
.
exceptions
.
ConnectionClosed
:
print
(
"WebSocket连接已关闭,停止发送通知"
)
await
log_message
(
"系统"
,
"WebSocket连接已关闭,停止发送通知"
)
self
.
_shutdown
=
True
except
Exception
as
e
:
print
(
f
"发送通知失败: {e}"
)
await
log_message
(
"错误"
,
f
"发送通知失败: {e}"
)
except
Exception
as
e
:
print
(
f
"通知处理器出错: {e}"
)
# 注意:这里不能使用 await,因为可能不在 async 上下文中
try
:
asyncio
.
create_task
(
log_message
(
"错误"
,
f
"通知处理器出错: {e}"
))
except
Exception
:
pass
return
callback
async
def
check_port_and_start_server
(
port
=
20111
,
host
=
'localhost'
):
"""检查端口并启动服务器"""
if
is_port_in_use
(
port
,
host
):
print
(
f
"错误: 端口 {port} 已被占用,无法启动服务"
)
await
log_message
(
"错误"
,
f
"端口 {port} 已被占用,无法启动服务"
)
return
False
print
(
f
"端口 {port} 可用,正在启动服务..."
)
await
log_message
(
"系统"
,
f
"端口 {port} 可用,正在启动服务"
)
server
=
await
websockets
.
serve
(
lambda
websocket
,
path
:
BLEClient
()
.
handle_client
(
websocket
,
path
),
host
,
port
,
...
...
@@ -632,19 +663,24 @@ async def check_port_and_start_server(port=20111, host='localhost'):
)
print
(
f
"WebSocket服务已启动: ws://{host}:{port}/scratch/ble"
)
print
(
"日志文件路径: ./b.log"
)
print
(
"日志文件路径: ./a.log"
)
await
log_message
(
"系统"
,
f
"WebSocket服务已启动: ws://{host}:{port}/scratch/ble"
)
# 执行自检测试
try
:
async
with
websockets
.
connect
(
f
"ws://{host}:{port}/scratch/ble"
)
as
websocket
:
print
(
"正在执行自检测试..."
)
await
log_message
(
"系统"
,
"正在执行自检测试..."
)
test_result
=
await
self_test
(
websocket
)
if
test_result
:
print
(
"自检测试成功: 服务正常运行"
)
await
log_message
(
"系统"
,
"自检测试成功: 服务正常运行"
)
else
:
print
(
"自检测试失败: 服务可能存在问题"
)
await
log_message
(
"警告"
,
"自检测试失败: 服务可能存在问题"
)
except
Exception
as
e
:
print
(
f
"自检测试异常: {str(e)}"
)
await
log_message
(
"错误"
,
f
"自检测试异常: {str(e)}"
)
return
server
...
...
Write
Preview
Styling with
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment