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
from rest_framework.exceptions import ParseError
import json
import time
def get_tyy_data(*args):
sc = socket.socket()
try:
sc.connect((args[0], int(args[1])))
except Exception:
raise ParseError("无法连接到采集器")
sc.send(b"R")
resp = sc.recv(1024)
if len(resp) < 8:
raise ParseError("设备未启动")
try:
json_data = resp[5:-4]
json_str = json_data.decode('utf-8')
res = json.loads(json_str)
except Exception:
raise
finally:
sc.close()
return res
host, port = args[0], args[1]
max_retries = 3
retry_delay = 0.5
for attempt in range(max_retries):
sc = None
try:
sc = socket.socket()
sc.connect((host, int(port)))
sc.sendall(b"R")
resp = sc.recv(1024)
if not resp:
raise ParseError("采集器返回空数据")
if len(resp) < 8:
raise ParseError("设备未启动")
json_data = resp[5:-4]
json_str = json_data.decode('utf-8')
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__':
print(get_tyy_data())