feat: get_tyy_data优化

This commit is contained in:
caoqianming 2025-05-16 10:59:10 +08:00
parent d1ccc9043f
commit 1d7c2ebb35
1 changed files with 34 additions and 18 deletions

View File

@ -1,26 +1,42 @@
import socket import socket
from rest_framework.exceptions import ParseError from rest_framework.exceptions import ParseError
import json import json
import time
def get_tyy_data(*args): def get_tyy_data(*args):
sc = socket.socket() host, port = args[0], args[1]
try: max_retries = 3
sc.connect((args[0], int(args[1]))) retry_delay = 0.5
except Exception:
raise ParseError("无法连接到采集器") for attempt in range(max_retries):
sc.send(b"R") sc = None
resp = sc.recv(1024) try:
if len(resp) < 8: sc = socket.socket()
raise ParseError("设备未启动") sc.connect((host, int(port)))
try: sc.sendall(b"R")
json_data = resp[5:-4] resp = sc.recv(1024)
json_str = json_data.decode('utf-8') if not resp:
res = json.loads(json_str) raise ParseError("采集器返回空数据")
except Exception: if len(resp) < 8:
raise raise ParseError("设备未启动")
finally: json_data = resp[5:-4]
sc.close() json_str = json_data.decode('utf-8')
return res res = json.loads(json_str)
return res
except ConnectionResetError:
if attempt == max_retries - 1:
raise ParseError("采集器重置了连接,重试次数已达上限")
time.sleep(retry_delay)
except socket.timeout:
raise ParseError("采集器连接超时")
except Exception as e:
raise ParseError(f"未知错误: {str(e)}")
finally:
if sc:
try:
sc.close()
except Exception:
pass
if __name__ == '__main__': if __name__ == '__main__':
print(get_tyy_data()) print(get_tyy_data())