342 lines
10 KiB
Python
342 lines
10 KiB
Python
import socket
|
|
import json
|
|
import logging
|
|
from typing import Optional, Dict, Any, Tuple
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
from config import config_manager
|
|
|
|
class UdpHandler:
|
|
"""UDP通信处理器"""
|
|
|
|
def __init__(self, remote_port: int, remote_host: str = 'localhost'):
|
|
"""初始化UDP处理器
|
|
|
|
Args:
|
|
remote_port: 远程端口号
|
|
"""
|
|
self.remote_address = (remote_host, remote_port)
|
|
|
|
self.sock = None
|
|
self.connected = False
|
|
|
|
# 初始化socket
|
|
self._init_socket()
|
|
|
|
def set_remote_port(self, remote_port: int):
|
|
"""设置远程端口号
|
|
|
|
Args:
|
|
remote_port: 远程端口号
|
|
"""
|
|
self.remote_address = (self.remote_address[0], remote_port)
|
|
|
|
# 重新初始化socket
|
|
self._init_socket()
|
|
|
|
@property
|
|
def port(self) -> int:
|
|
"""本地端口号"""
|
|
return self.remote_address[1]
|
|
|
|
def _init_socket(self):
|
|
"""初始化UDP socket"""
|
|
try:
|
|
# 关闭旧socket
|
|
if self.sock:
|
|
self.sock.close()
|
|
|
|
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
# self.sock.bind((self.remote_address[0], self.remote_address[1] + 10000))
|
|
self.connected = True
|
|
logger.info(f"UDP socket initialized, local port: {self.remote_address[1] + 10000}, remote: {self.remote_address}")
|
|
except Exception as e:
|
|
logger.error(f"Failed to initialize UDP socket: {e}")
|
|
raise
|
|
|
|
def send_command(self, command: Dict[str, Any]) -> bool:
|
|
"""发送命令到MATLAB网关
|
|
|
|
Args:
|
|
command: 命令字典
|
|
|
|
Returns:
|
|
bool: 发送是否成功
|
|
"""
|
|
try:
|
|
if not self.sock:
|
|
logger.error("UDP socket not initialized")
|
|
return False
|
|
|
|
message = json.dumps(command)
|
|
self.sock.sendto(message.encode(), self.remote_address)
|
|
logger.debug(f"Sent command to {self.remote_address}: {command}")
|
|
return True
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to send command: {e}")
|
|
return False
|
|
|
|
def send_status_cmd(self):
|
|
"""发送状态查询命令"""
|
|
command = {
|
|
'command': 'status'
|
|
}
|
|
return self.send_command(command)
|
|
|
|
def send_compute_cmd(self, file_path: str) -> bool:
|
|
"""发送计算命令
|
|
|
|
Args:
|
|
file_path: .mat文件路径
|
|
|
|
Returns:
|
|
bool: 发送是否成功
|
|
"""
|
|
command = {
|
|
'command': 'compute',
|
|
'file_path': file_path
|
|
}
|
|
return self.send_command(command)
|
|
|
|
def send_start_cmd(self, cfg_path: str) -> bool:
|
|
"""发送启动命令
|
|
|
|
Args:
|
|
cfg_path: 配置文件路径
|
|
|
|
Returns:
|
|
bool: 发送是否成功
|
|
"""
|
|
command = {
|
|
'command': 'start',
|
|
'cfg_path': cfg_path
|
|
}
|
|
return self.send_command(command)
|
|
|
|
def send_stop_cmd(self) -> bool:
|
|
"""发送停止命令
|
|
|
|
Returns:
|
|
bool: 发送是否成功
|
|
"""
|
|
command = {
|
|
'command': 'stop'
|
|
}
|
|
return self.send_command(command)
|
|
|
|
def receive_data(self, timeout: float = 2.0) -> Optional[Any]:
|
|
"""接收数据
|
|
|
|
Args:
|
|
timeout: 超时时间(秒)
|
|
|
|
Returns:
|
|
接收到的数据,如果失败或超时返回None
|
|
"""
|
|
try:
|
|
if not self.sock:
|
|
logger.error("UDP socket not initialized")
|
|
return None
|
|
|
|
self.sock.settimeout(timeout)
|
|
|
|
try:
|
|
data, addr = self.sock.recvfrom(10240)
|
|
self.sock.settimeout(None)
|
|
|
|
logger.debug(f"Received data from {addr}: {len(data)} bytes")
|
|
|
|
# 解码数据
|
|
if not isinstance(data, str):
|
|
data = data.decode()
|
|
|
|
# 解析JSON
|
|
msg = json.loads(data)
|
|
|
|
return msg
|
|
|
|
except socket.timeout:
|
|
logger.warning(f"Timeout waiting for response after {timeout} seconds")
|
|
return None
|
|
|
|
except json.JSONDecodeError as e:
|
|
logger.error(f"Failed to parse JSON response: {e}")
|
|
logger.debug(f"Raw data: {data}")
|
|
return None
|
|
except Exception as e:
|
|
logger.error(f"Failed to receive data: {e}")
|
|
return None
|
|
|
|
def compute(self, mat_file_path: str, timeout: float = 2.0) -> Optional[str]:
|
|
"""执行计算操作
|
|
|
|
Args:
|
|
mat_file_path: .mat文件路径
|
|
timeout: 超时时间(秒)
|
|
|
|
Returns:
|
|
输出文件路径,如果失败返回None
|
|
"""
|
|
try:
|
|
# 清空接收缓冲区
|
|
self.receive_data(timeout=0.001)
|
|
|
|
# 发送计算命令
|
|
if not self.send_compute_cmd(mat_file_path):
|
|
logger.error("Failed to send compute command")
|
|
return None
|
|
|
|
# 接收结果
|
|
result = self.receive_data(timeout=timeout)
|
|
if result is not None and 'result' in result:
|
|
result = result['result']
|
|
logger.info(f"Compute result: {result}")
|
|
return result
|
|
|
|
except Exception as e:
|
|
logger.error(f"Compute operation failed: {e}")
|
|
return None
|
|
|
|
def status(self, timeout: float = 2.0) -> Optional[Dict[str, Any]]:
|
|
"""查询状态
|
|
|
|
Args:
|
|
timeout: 超时时间(秒)
|
|
|
|
Returns:
|
|
状态信息字典,如果失败返回None
|
|
"""
|
|
try:
|
|
# 清空接收缓冲区
|
|
self.receive_data(timeout=0.001)
|
|
|
|
# 发送状态查询命令
|
|
if not self.send_status_cmd():
|
|
logger.error("Failed to send status command")
|
|
return None
|
|
|
|
# 接收结果
|
|
result = self.receive_data(timeout=timeout)
|
|
|
|
print()
|
|
print(result)
|
|
print()
|
|
|
|
logger.info(f"Status result: {result}")
|
|
return result
|
|
|
|
except Exception as e:
|
|
logger.error(f"Status query failed: {e}")
|
|
return None
|
|
|
|
def _udp_status_available(self, response) -> bool:
|
|
if not response:
|
|
return False
|
|
try:
|
|
status = response['result']
|
|
idle_time = response['idle_time']
|
|
run_time = response['run_time']
|
|
compute_count = response['compute_count']
|
|
if idle_time > 3600:
|
|
return True
|
|
if compute_count == 0:
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"Failed to parse UDP status response: {e}")
|
|
return False
|
|
return True
|
|
|
|
def is_udp_port_in_use(self, port):
|
|
maps = config_manager.get_udp_map()
|
|
if not maps:
|
|
return False
|
|
for dev_id, _port in maps.items():
|
|
if _port == port:
|
|
return True
|
|
return False
|
|
|
|
def search_for_available_udp_port(self) -> bool:
|
|
"""搜索可用的UDP端口
|
|
|
|
Returns:
|
|
bool: 是否找到可用端口
|
|
"""
|
|
|
|
#先检查当前端口是否可用
|
|
response = self.status()
|
|
logger.info(f"UDP port {self.port} status: {response}")
|
|
|
|
if self._udp_status_available(response):
|
|
logger.info(f"UDP port {self.port} is available")
|
|
self.available = True
|
|
return True
|
|
|
|
# 检查其他端口
|
|
self.available = False
|
|
port = config_manager.get('udp.port', 15000)
|
|
num = config_manager.get('udp.num', 10)
|
|
for i in range(num):
|
|
self.set_remote_port(port + i)
|
|
response = self.status()
|
|
logger.info(f"UDP port {self.port} status: {response}")
|
|
if self._udp_status_available(response) and not self.is_udp_port_in_use(port + i):
|
|
logger.info(f"UDP port {self.port} is available")
|
|
self.available = True
|
|
break
|
|
|
|
return self.available
|
|
|
|
def is_available(self) -> bool:
|
|
"""检查端口是否可用
|
|
|
|
Returns:
|
|
bool: 是否可用
|
|
"""
|
|
response = self.status()
|
|
logger.info(f"UDP port {self.port} status: {response}")
|
|
if self._udp_status_available(response):
|
|
logger.info(f"UDP port {self.port} is available")
|
|
self.available = True
|
|
else:
|
|
logger.info(f"UDP port {self.port} is not available")
|
|
self.available = False
|
|
|
|
return self.available
|
|
|
|
def remove_dev_by_port(self,port) -> bool:
|
|
maps = config_manager.get_udp_map()
|
|
for dev_id, _port in maps.items():
|
|
if _port == port:
|
|
config_manager.del_udp_map(dev_id)
|
|
return True
|
|
return False
|
|
|
|
def close(self):
|
|
"""关闭UDP socket"""
|
|
try:
|
|
if self.sock:
|
|
self.sock.close()
|
|
self.sock = None
|
|
self.connected = False
|
|
logger.info("UDP socket closed")
|
|
except Exception as e:
|
|
logger.error(f"Error closing UDP socket: {e}")
|
|
|
|
def is_connected(self) -> bool:
|
|
"""检查是否已连接
|
|
|
|
Returns:
|
|
bool: 是否已连接
|
|
"""
|
|
return self.connected
|
|
|
|
def __enter__(self):
|
|
"""上下文管理器入口"""
|
|
return self
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
"""上下文管理器出口"""
|
|
self.close()
|