feat: 写指令也短读0.3s捕获机器的ERR回包

之前 expect_reply=False 直接关 socket, 机器若回 ERR 完全感知不到,
表现就是"接口200但实际没动作"。改为写完后短读最多一行, 拿到
ERR/'!' 开头直接报错; 超时则照旧视为成功放行。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
caoqianming 2026-05-18 15:16:27 +08:00
parent 3304371560
commit 2b3aaf8879
1 changed files with 26 additions and 9 deletions

View File

@ -27,8 +27,7 @@ class CoderClient:
try:
with socket.create_connection((self.ip, self.port), timeout=self.timeout) as s:
s.sendall(frame)
if not expect_reply:
return b""
if expect_reply:
buf = b""
while CR not in buf:
chunk = s.recv(256)
@ -36,6 +35,24 @@ class CoderClient:
break
buf += chunk
return buf
# 写指令: 短暂等待, 捕获机器拒绝(ERR/!); 超时则视为成功
s.settimeout(0.3)
try:
buf = b""
while CR not in buf:
chunk = s.recv(256)
if not chunk:
break
buf += chunk
except socket.timeout:
buf = b""
if buf:
text = buf.rstrip(b"\r\n").decode("latin-1", errors="replace")
if text.startswith("ERR") or text.startswith("!"):
raise CoderError(f"喷码机拒绝指令 {frame!r}: {text}")
return b""
except CoderError:
raise
except (socket.timeout, OSError) as e:
raise CoderError(f"喷码通讯失败 {self.ip}:{self.port} - {e}")