first commit
This commit is contained in:
80
code/system/services/vdes_data_receive.py
Normal file
80
code/system/services/vdes_data_receive.py
Normal file
@@ -0,0 +1,80 @@
|
||||
import socket
|
||||
import logging
|
||||
import time
|
||||
import json
|
||||
import struct
|
||||
import threading
|
||||
from fuadmin import settings
|
||||
from system import apps
|
||||
from vdes_utils.vdes_data_parsing import VdesDataParsing
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class VDESSocketMonitor:
|
||||
_instance = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
def __new__(cls):
|
||||
with cls._lock:
|
||||
if not cls._instance:
|
||||
cls._instance = super().__new__(cls)
|
||||
cls._instance._initialized = False
|
||||
return cls._instance
|
||||
|
||||
def __init__(self):
|
||||
if self._initialized:
|
||||
return
|
||||
self._initialized = True
|
||||
|
||||
self.host = getattr(settings, 'VDES_MONITOR_HOST', 'localhost')
|
||||
self.port = getattr(settings, 'VDES_MONITOR_PORT', 8083)
|
||||
self.buffer_size = getattr(settings, 'VDES_BUFFER_SIZE', 4096)
|
||||
|
||||
self.running = False
|
||||
self.thread = None
|
||||
self.vdes_data_parsing = VdesDataParsing()
|
||||
logger.info(f"VDES 监控服务初始化完成 - {self.host}:{self.port}")
|
||||
|
||||
def start(self):
|
||||
if self.running:
|
||||
logger.warning("监控服务已在运行中")
|
||||
return
|
||||
|
||||
self.running = True
|
||||
self.thread = threading.Thread(
|
||||
target=self._monitor_loop,
|
||||
name="VDES-Monitor-Thread",
|
||||
daemon=False
|
||||
)
|
||||
self.thread.start()
|
||||
logger.info("VDES 监控服务已启动")
|
||||
|
||||
def stop(self):
|
||||
self.running = False
|
||||
if self.thread and self.thread.is_alive():
|
||||
self.thread.join(timeout=5)
|
||||
logger.info("VDES 监控服务已停止")
|
||||
|
||||
def _monitor_loop(self):
|
||||
while self.running:
|
||||
try:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
|
||||
print(f"尝试连接到服务器 {self.host}:{self.port}")
|
||||
sock.connect((self.host, self.port))
|
||||
print(f"成功连接到服务器 {self.host}:{self.port}")
|
||||
while self.running:
|
||||
data = sock.recv(self.buffer_size)
|
||||
if data:
|
||||
# print(data)
|
||||
self.vdes_data_parsing.parse_vdes_data(data)
|
||||
except (ConnectionRefusedError, TimeoutError) as e:
|
||||
print(f"连接失败: {e}")
|
||||
except Exception as e:
|
||||
print(f"连接异常: {e}")
|
||||
|
||||
# 如果服务仍在运行,则等待30秒后重新尝试连接
|
||||
if self.running:
|
||||
print("等待30秒后重新尝试连接...")
|
||||
time.sleep(30)
|
||||
|
||||
Reference in New Issue
Block a user