feat: get_tyy_data优化
This commit is contained in:
parent
d1ccc9043f
commit
1d7c2ebb35
|
@ -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]
|
||||||
|
max_retries = 3
|
||||||
|
retry_delay = 0.5
|
||||||
|
|
||||||
|
for attempt in range(max_retries):
|
||||||
|
sc = None
|
||||||
try:
|
try:
|
||||||
sc.connect((args[0], int(args[1])))
|
sc = socket.socket()
|
||||||
except Exception:
|
sc.connect((host, int(port)))
|
||||||
raise ParseError("无法连接到采集器")
|
sc.sendall(b"R")
|
||||||
sc.send(b"R")
|
|
||||||
resp = sc.recv(1024)
|
resp = sc.recv(1024)
|
||||||
|
if not resp:
|
||||||
|
raise ParseError("采集器返回空数据")
|
||||||
if len(resp) < 8:
|
if len(resp) < 8:
|
||||||
raise ParseError("设备未启动")
|
raise ParseError("设备未启动")
|
||||||
try:
|
|
||||||
json_data = resp[5:-4]
|
json_data = resp[5:-4]
|
||||||
json_str = json_data.decode('utf-8')
|
json_str = json_data.decode('utf-8')
|
||||||
res = json.loads(json_str)
|
res = json.loads(json_str)
|
||||||
except Exception:
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
sc.close()
|
|
||||||
return res
|
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())
|
Loading…
Reference in New Issue