factory/apps/em/cd.py

42 lines
1.3 KiB
Python

import socket
from rest_framework.exceptions import ParseError
import json
import time
def get_tyy_data(*args):
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("采集器返回空数据")
elif 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())