Compare commits
2 Commits
4b52c28b5e
...
b8c799b938
Author | SHA1 | Date |
---|---|---|
|
b8c799b938 | |
|
5a98d1bea7 |
|
@ -16,7 +16,7 @@ def get_checksum(body_msg):
|
|||
|
||||
def handle_bytes(arr):
|
||||
if len(arr) < 8:
|
||||
return "返回数据长度错误"
|
||||
return f"返回数据长度错误-{arr}"
|
||||
|
||||
if arr[0] != 0xEB or arr[1] != 0x90:
|
||||
return "数据头不正确"
|
||||
|
@ -208,3 +208,36 @@ def get_tyy_data(*args, retry=1):
|
|||
raise ParseError(f'采集器返回数据错误-{res}')
|
||||
else:
|
||||
return res
|
||||
|
||||
|
||||
def get_tyy_data_3(*args, retry=2):
|
||||
host, port = args[0], int(args[1])
|
||||
for attempt in range(retry):
|
||||
try:
|
||||
# 每次请求都新建连接(确保无共享状态)
|
||||
with socket.create_connection((host, port), timeout=10) as sc:
|
||||
sc.sendall(b"R")
|
||||
|
||||
# 接收完整响应(避免数据不完整)
|
||||
# resp = b""
|
||||
# while True:
|
||||
# chunk = sc.recv(4096)
|
||||
# if not chunk:
|
||||
# break
|
||||
# resp += chunk
|
||||
resp = sc.recv(4096)
|
||||
if not resp:
|
||||
raise ParseError("设备未启动")
|
||||
|
||||
res = handle_bytes(resp)
|
||||
if isinstance(res, str):
|
||||
raise ParseError(f"采集器返回数据错误: {res}")
|
||||
return res
|
||||
except (socket.timeout, ConnectionError) as e:
|
||||
if attempt == retry - 1: # 最后一次尝试失败才报错
|
||||
raise ParseError(f"采集器连接失败: {str(e)}")
|
||||
time.sleep(0.5) # 失败后等待 1s 再重试
|
||||
except ParseError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise ParseError(f"未知错误: {str(e)}")
|
Loading…
Reference in New Issue