import socket import struct
import time
class MCRemoteClient:
"""三菱MC协议3E帧通信客户端"""
def __init__(self, plc_ip='192.168.1.100', plc_port=1025):
self.plc_ip = plc_ip
self.plc_port = plc_port
self.sock = None
self.connect()
def connect(self):
"""建立TCP连接,超时5秒"""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(5.0)
try:
self.sock.connect((self.plc_ip, self.plc_port))
print(f"[OK] 连接成功 -> {self.plc_ip}:{self.plc_port}")
except Exception as e:
print(f"[ERROR] 连接失败: {e}")
self.sock = None
def _build_3e_frame(self, subcommand, data):
"""构建3E帧格式
帧结构: 帧头(2B) + 网络编号(1B) + PC编号(1B) +
请求目标(1B) + 定时器(2B) + 命令(2B) +
子命令(2B) + 数据体(N)
"""
frame = b'\\x50\\x00' # 帧头固定
frame += b'\\x00' # 网络编号
frame += b'\\xff' # PC编号(默认255)
frame += b'\\xff\\x03' # 请求目标
frame += b'\\x00\\x3c' # 定时器 60秒
frame += b'\\x04\\x01' # 命令:批量读取
frame += struct.pack('>H', subcommand) # 子命令
frame += data
return frame
def send_command(self, command_bytes):
"""发送命令并接收响应"""
if not self.sock:
print("[ERROR] 未连接")
return None
try:
self.sock.send(command_bytes)
response = self.sock.recv(2048)
return response
except socket.timeout:
print("[ERROR] 接收超时")
return None