Files
windows-fenjian/core/scale/reader.py
T

600 lines
26 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""电子秤 RS232 读取(Windows 版,自己解析帧)。
帧协议模板(安卓版由京源 SDK 隐式完成,此处显式实现):
"ST,GS,+ 1.234kg" ST=稳定 GS=毛重 → 取值
"US,GS,..." US=不稳 → 不稳(不出值)
"OL" 超载 → 拒绝
"-----------" 负序号/不稳 → 不稳
纯数字行 通用容错 → 取值(按配置容差判稳)
有效性三件套(对齐 WeighManager):
去重 5g / 心跳 60s / 5s 无新帧即失效。
pause()/resume() 供打印前释放 USB 总线;resume 后强制等新帧。
"""
import re
import time
import random
import threading
from collections import deque
try:
import serial
except ImportError:
serial = None
def list_serial_ports():
"""枚举本机串口(设置页“扫描串口”用)"""
try:
from serial.tools import list_ports
out = []
for p in list_ports.comports():
out.append({'port': p.device,
'description': getattr(p, 'description', '') or ''})
return out
except Exception:
return []
_STABLE_RE = re.compile(r'\bST\b')
_UNSTABLE_RE = re.compile(r'\bUS\b')
_OVERLOAD_RE = re.compile(r'\bOL\b')
_NUM_RE = re.compile(r'[-+]?\d+(?:\.\d+)?')
_SIGN_GAP_RE = re.compile(r'([-+])\s+') # "- 1.234" → "-1.234"
_UNIT_RE = re.compile(r'([-+]?\d+(?:\.\d+)?)\s*(kg|g|lb|t)\b', re.I)
DEDUP_DELTA_KG = 0.005
HEARTBEAT_MS = 60_000
FRAME_STALE_MS = 5_000
# 秤吐的数一般是 kg / g(部分进口秤 lb),内部一律换算成 kg:
# 上报、判存在、判稳、台账全用同一口径,不会出现界面 kg、后台 g 的错位。
UNIT_TO_KG = {'kg': 1.0, 'g': 0.001, 'lb': 0.45359237, 't': 1000.0}
# 常见电子秤的去皮 / 置零串口命令(现场自动探测用)。
# 国内台秤绝大多数是耀华 XK3190 系(ESC T / ESC Z)或纯 ASCII T/Z;
# 托利多 MT-SICS 是 T\r\n / Z\r\n。探测时一条条发,谁把毛重打到 0 就算谁。
CMD_FAMILIES = [
('耀华 XK3190(A12 / A9 / A27 等)', 'hex:1B 54', 'hex:1B 5A'),
('通用 ASCII T\\r / Z\\r', 'hex:54 0D', 'hex:5A 0D'),
('通用 ASCII T\\r\\n / Z\\r\\n(托利多)', 'hex:54 0D 0A', 'hex:5A 0D 0A'),
('通用 ASCII T / Z(单字节)', 'hex:54', 'hex:5A'),
('大华 / 顶尖 T␠\\r / Z␠\\r', 'hex:54 20 0D', 'hex:5A 20 0D'),
]
def _unit_of(line, default='kg'):
"""从帧里猜单位:'1.234kg' → kg,'1234 g' → g;猜不到用默认"""
for m in _UNIT_RE.finditer(line):
u = m.group(2).lower()
if u:
return u
return default
def parse_frame(line, unit='auto', pattern=None):
"""返回 (weight_kg or None, stable: bool|None, overload: bool)
unit: 'auto' 按帧里的单位后缀判断;也可指定 kg/g/lb 强制。
pattern: 可选正则,第 1 个分组即重量(帧里有时间/流水号等干扰数字时用)。
"""
if not line:
return None, None, False
if _OVERLOAD_RE.search(line):
return None, None, True
text = _SIGN_GAP_RE.sub(r'\1', line)
raw = None
if pattern:
try:
m = re.search(pattern, text)
if m:
raw = float(m.group(1))
except (re.error, IndexError, ValueError):
raw = None
if raw is None:
m = _NUM_RE.search(text)
if not m:
return None, None, False
try:
raw = float(m.group())
except ValueError:
return None, None, False
u = _unit_of(text, 'kg') if str(unit).lower() == 'auto' else str(unit).lower()
w = raw * UNIT_TO_KG.get(u, 1.0)
if _UNSTABLE_RE.search(line):
return w, False, False
if _STABLE_RE.search(line):
return w, True, False
return w, None, False # 无状态前缀,交给容差判稳
class ScaleReader:
def __init__(self, cfg):
self.cfg = cfg.get('scale', {})
self.weight = 0.0
self.last_frame_at = 0.0 # 单调时钟
self.connected = False
self.error = None
self.overload = False
self._history = []
self._paused = False
self._lock = threading.RLock() # 可重入:state() 持锁调用 is_fresh()
self._tare = 0.0 # 去皮偏移(毛重 - 去皮 = 净重)
self._zero = 0.0 # 置零偏移(秤吐的原始值 - 置零 = 毛重)
self._ser = None # 当前串口对象(发去皮/置零命令用)
self._cmd_lock = threading.Lock()
self._raw = deque(maxlen=40) # 最近原始帧(诊断用:原文 + 十六进制)
self._sim_target = None
self._sim_current = 0.0
self._running = False
self._reload = False # 热切换请求(reconfigure 置位)
def start(self):
self._running = True
threading.Thread(target=self._loop, daemon=True).start()
def stop(self):
self._running = False
def release(self, wait=1.5):
"""停读并立即放开串口句柄(设备自动识别要独占串口探测用)。
只 stop() 的话读线程还阻塞在 ser.read(timeout=1) 里,句柄没关,
探测端会拿到「拒绝访问」——现场看着就像「串口被别的程序占用」。
这里直接把句柄关掉,读线程下一拍就退出。
注意:退出登录时也必须走这个(FlowEngine.stop 已改),否则旧引擎
一直占着 COM 口,新引擎登录后报「COM3 被其它程序占用」,现场看到
的就是「重新登录后秤不认了」。
"""
self.stop()
ser = getattr(self, '_ser', None)
if ser is not None:
try:
ser.close()
except Exception:
pass
with self._lock:
if self._ser is ser:
self._ser = None
t0 = time.time()
while time.time() - t0 < wait and getattr(self, '_ser', None) is not None:
time.sleep(0.05)
def reconfigure(self, new_scale_cfg):
"""运行中切换秤配置(设置页选完串口立即生效,无需重启程序)。
串口读阻塞在 ser.read(timeout=1),切换最多延迟 1~3 秒生效。
"""
with self._lock:
self.cfg = dict(new_scale_cfg or {})
self._reload = True
self.connected = False
self.error = None
self.overload = False
self.weight = 0.0
self._history = []
self.last_frame_at = 0.0
self._tare = 0.0
self._zero = 0.0
self._ser = None
self._raw.clear()
def pause(self):
"""打印前释放 USB 总线:暂停解析并作废帧时间戳(必须等新帧)"""
with self._lock:
self._paused = True
self.last_frame_at = 0.0
def resume(self):
with self._lock:
self._paused = False
# ---------- 模拟 ----------
def sim_put(self, kg):
self._sim_target = kg
def sim_clear(self):
self._sim_target = None
self._sim_current = 0.0
# ---------- 去皮 / 置零 ----------
# 现场三种情况:
# ① 秤支持串口命令(耀华 XK3190 系、托利多 MT-SICS…)→ 发命令,秤面
# 自己归零,软件偏移清 0(避免扣两遍)。发完必须看秤有没有反应。
# ② 秤只发不收(便宜的连续发送台秤)→ 只能软件去皮:记住当前毛重当
# 偏移,净重 = 毛重 - 偏移,秤面不变。这时必须明说,不能假装成功。
# ③ config 里填了命令但协议不对 → 命令发出去了、秤没动,要报「没反应」
# 而不是「已去皮」,否则现场以为按了没用。
# 现场教训(2026-11-04):以前一律返回「已置零(软件清零)」,
# 用户按了半天问「怎么秤上没有变化」——按钮根本没落到秤上。
# 现在的口径:
# 去皮 → 记 _tare(净重归 0),秤面不变但界面净重归 0;空秤若有零点
# 漂移(实测 -0.020 kg),每件都会少算 20 g,先「置零」再「去皮」。
# 置零 → 记 _zero(毛重归 0),界面立刻 0.000;只允许空秤(±zero_range_kg)
# 时做,秤上有货直接拒绝,免得把货重当零点漂移吃掉。
def _send(self, cmd):
"""把命令写给秤:ASCII 直发,或以 hex: 开头的十六进制字节"""
cmd = (cmd or '').strip()
if not cmd:
return False, '未配置命令'
try:
data = bytes.fromhex(cmd[4:].replace(' ', '')) \
if cmd.lower().startswith('hex:') else cmd.encode('ascii')
except Exception as e: # noqa: BLE001
return False, '命令格式错误: %s' % e
with self._cmd_lock:
ser = self._ser
if ser is None or not getattr(ser, 'is_open', False):
return False, '串口未连接'
try:
ser.write(data)
ser.flush()
except Exception as e: # noqa: BLE001
return False, '发送失败: %s' % e
return True, ''
def send(self, cmd):
"""给设置页「测试命令」用:只发不等结果"""
return self._send(cmd)
def _wait_gross(self, seconds, until):
"""等秤面的毛重满足条件(发命令后看它到底动没动)"""
t0 = time.monotonic()
while time.monotonic() - t0 < seconds:
with self._lock:
g, fresh = self.weight, self.is_fresh()
if fresh and until(g):
return True, g
time.sleep(0.05)
with self._lock:
return False, self.weight
def last_frames(self, n=6):
"""最近 n 条原始帧(设置页诊断区显示,判断协议用)"""
with self._lock:
return list(self._raw)[-int(n):]
def _gross(self):
"""毛重 = 秤吐的原始值 − 置零偏移(软件置零后秤面不变,界面归 0)"""
with self._lock:
return round(self.weight - self._zero, 3)
def tare(self):
"""去皮:返回 (ok, 提示语)"""
cmd = str(self.cfg.get('tare_cmd') or '').strip()
with self._lock:
gross, fresh = round(self.weight - self._zero, 3), self.is_fresh()
if not cmd:
if not fresh:
return False, '秤没有数据(%s),无法去皮' % (
self.error or '未连接')
with self._lock:
self._tare = gross
return True, ('软件去皮(当前毛重 %.3f kg,净重已归 0;秤面不变,'
'要让秤面归零按秤面板【去皮】键)' % gross)
ok_cmd, err = self._send(cmd)
if not ok_cmd:
if fresh:
with self._lock:
self._tare = gross
return True, '去皮命令发不出去(%s),已软件去皮 %.3f kg' % (
err, gross)
return False, '去皮命令发不出去:%s' % err
hit, g = self._wait_gross(1.5, lambda w: abs(w) <= 0.02)
if hit:
with self._lock:
self._tare = 0.0
self._zero = 0.0
return True, '秤已去皮(秤面归零)'
if abs(gross) <= 0.03: # 秤面本来就在零点,看不出变化
with self._lock:
self._tare = 0.0
return True, '已发去皮命令(秤面本来就在零点附近,看不出变化)'
with self._lock:
self._tare = gross
return False, ('去皮命令发出去了,但秤面还是 %.3f kg —— 这台秤不支持这个'
'命令,已临时软件去皮;可到 设置→电子秤→去皮/置零… 自动探测'
% g)
def zero(self):
"""置零:让界面的毛重回到 0.000(去皮偏移一并清掉)。
现场教训(2026-11-04):以前这里只把去皮偏移清 0,秤空着读 -0.020 kg
时按「置零」屏幕一动不动,看着就像按钮坏了。现在改成真的记一个
置零偏移:毛重 = 原始值 − 偏移,按完界面立刻显示 0.000。
置零只能在空秤(±zero_range_kg)时做,秤上有货时拒绝——否则一件货
的重量会被当成零点漂移吃掉。
"""
cmd = str(self.cfg.get('zero_cmd') or '').strip()
limit = abs(float(self.cfg.get('zero_range_kg', 0.05) or 0.05))
with self._lock:
gross, fresh = round(self.weight - self._zero, 3), self.is_fresh()
if cmd:
ok_cmd, err = self._send(cmd)
if ok_cmd:
hit, g = self._wait_gross(1.5, lambda w: abs(w) <= 0.02)
if hit:
with self._lock:
self._zero = 0.0
self._tare = 0.0
return True, '秤已置零(秤面归零)'
# 秤不认这条命令 → 往下走软件置零,并把原因说清楚
why = '秤面还是 %.3f kg,这台秤不支持串口置零' % g
else:
why = '置零命令发不出去(%s)' % err
else:
why = '这台秤没配置零命令'
if not fresh:
return False, '秤没有数据(%s),无法置零' % (self.error or '未连接')
if abs(gross) <= 0.001:
with self._lock:
self._tare = 0.0
return True, '已经是 0.000 kg,不用置零'
if abs(gross) > limit:
return False, ('秤上还有 %.3f kg,置零只能在空秤时做 —— 货物请先拿下来;'
'要扣筐/托盘请按「去皮」' % gross)
with self._lock:
self._zero = round(self._zero + gross, 3)
self._tare = 0.0
return True, ('已置零:%.3f → 0.000 kg(%s,界面归零,秤面显示不变)'
% (gross, why))
def probe_tare_cmd(self, families=None, before=None):
"""自动探测去皮命令:秤上放好重物(≥0.2kg)后调用。
逐条发常见命令,哪条把毛重打到 0 就认定是这家协议,同时带出配对的
置零命令。返回 (命中元组 or None, 说明文字)。
"""
if not self.is_fresh():
return None, '秤没有数据,先确认串口能读到重量'
base = self._gross()
if abs(base) < 0.05:
return None, '秤上几乎是空的(%.3f kg),请先放一个 0.2kg 以上的东西' % base
tried = []
for name, tare_cmd, zero_cmd in (families or CMD_FAMILIES):
ok, err = self._send(tare_cmd)
if not ok:
return None, '命令发不出去:%s' % err
hit, g = self._wait_gross(1.6, lambda w: abs(w) <= 0.02)
if hit:
with self._lock:
self._zero = 0.0
self._tare = 0.0
return (name, tare_cmd, zero_cmd), \
'命中「%s」:%s → 秤面已归零' % (name, tare_cmd)
tried.append('%s 后 %.3f' % (name.split('(')[0], g))
return None, ('试了 %d 种常见命令秤都没反应(%s)。这台秤多半只发不收,'
'去皮只能按秤面板上的【去皮】键' % (len(tried), ';'.join(tried)))
# ---------- 循环 ----------
def _loop(self):
while self._running:
self._reload = False
if self.cfg.get('simulate'):
self._sim_loop()
else:
self._serial_loop()
if not self._reload: # 非热切换退出则结束线程
break
def _accept(self, w, stable_flag):
now = time.monotonic()
with self._lock:
if self._paused:
return
self.overload = False
self.weight = w
self.last_frame_at = now
self.connected = True
self._history.append((now, w, stable_flag))
n = int(self.cfg.get('stable_count', 5))
if len(self._history) > n:
self._history = self._history[-n:]
def _sim_loop(self):
t0 = time.monotonic()
while self._running and not self._reload:
if self._paused:
time.sleep(0.2)
continue
self._sim_auto(t0)
t = self._sim_target
nxt = 0.0 if t is None else max(
0.0, self._sim_current + (t - self._sim_current) * 0.8
+ random.uniform(-0.0005, 0.0005))
self._sim_current = nxt
self._accept(nxt, None)
time.sleep(0.2)
def _sim_auto(self, t0):
"""离线演示:模拟秤自己「放货 → 稳住 → 取走」循环。
`scale.sim_loop_kg` > 0 时启用(不设就还是原来那样一直 0,
等外部 sim_put 喂重量)。周期三个参数:
sim_loop_hold_s 空秤多久后放货(默认 2.5s,进来先看清界面)
sim_loop_keep_s 货在秤上停多久(默认 6s,够抓拍+识别+等着确认)
sim_loop_idle_s 取走后空多久(默认 3s,让「拿走即提交」判完)
重量是平滑逼近的(每 0.2s 走 80%),2 秒左右才稳;识别是在稳住
之后才起流程,所以 hold 给到 2.5s 足够。
"""
kg = float(self.cfg.get('sim_loop_kg') or 0)
if kg <= 0:
return
hold = max(0.0, float(self.cfg.get('sim_loop_hold_s', 2.5) or 0))
keep = max(1.0, float(self.cfg.get('sim_loop_keep_s', 6.0) or 6.0))
idle = max(0.5, float(self.cfg.get('sim_loop_idle_s', 3.0) or 3.0))
total = hold + keep + idle
phase = (time.monotonic() - t0) % total
# 每轮重量抖一点(sim_loop_jitter_kg,同一轮里恒定):
# 演示时每轮都是 3.000 kg,会被「疑似重复收货」当成同一件货拦下。
jit = max(0.0, float(self.cfg.get('sim_loop_jitter_kg') or 0))
if jit > 0:
cyc = int((time.monotonic() - t0) // total)
kg = max(0.2, kg + random.Random(cyc * 7919).uniform(-jit, jit))
self._sim_target = kg if hold <= phase < hold + keep else None
def _serial_loop(self):
if serial is None:
with self._lock:
self.error = '未安装 pyserial'
return
while self._running and not self._reload:
ser = None
try:
ser = serial.Serial(
port=self.cfg.get('port', 'COM3'),
baudrate=int(self.cfg.get('baudrate', 9600)),
bytesize=int(self.cfg.get('bytesize', 8)),
parity=self.cfg.get('parity', 'N'),
stopbits=float(self.cfg.get('stopbits', 1)),
timeout=1)
with self._lock:
self._ser = ser
if not self._reload:
self.error = None
buf = b''
unit = self.cfg.get('unit', 'auto')
pattern = (self.cfg.get('pattern') or '').strip() or None
poll_cmd = (self.cfg.get('poll_cmd') or '').strip()
poll_sec = max(0.2, float(self.cfg.get('poll_ms', 500)) / 1000.0)
last_poll = time.monotonic()
while self._running and not self._reload:
# 应答式秤:长时间没帧就主动问一句(连续发送的秤不用填)
if poll_cmd and time.monotonic() - last_poll >= poll_sec:
last_poll = time.monotonic()
self._send(poll_cmd)
chunk = ser.read(64)
if not chunk:
continue
last_poll = time.monotonic()
buf += chunk
while b'\n' in buf or b'\r' in buf:
idxs = [i for i in (buf.find(b'\n'), buf.find(b'\r'))
if i >= 0]
idx = min(idxs)
raw = buf[:idx]
line = raw.decode('gbk', errors='ignore').strip()
buf = buf[idx + 1:]
if not line:
continue
with self._lock:
self._raw.append({
't': time.strftime('%H:%M:%S'),
'text': line[:60],
'hex': raw[:40].hex(' ').upper()})
w, stable, overload = parse_frame(line, unit, pattern)
if overload:
with self._lock:
self.overload = True
continue
if w is not None and stable is not False:
self._accept(w, stable)
except Exception as e:
with self._lock:
self.connected = False
self.error = str(e)
self.last_frame_at = 0.0
self._ser = None
if ser:
try:
ser.close()
except Exception:
pass
if self._reload:
break
time.sleep(3)
# ---------- 对外 ----------
def is_fresh(self, stale_ms=FRAME_STALE_MS):
with self._lock:
if self.last_frame_at <= 0 or self._paused:
return False
age = (time.monotonic() - self.last_frame_at) * 1000.0
return 0 <= age <= stale_ms
def is_stable(self, delta_kg, need_n=5):
with self._lock:
if len(self._history) < need_n:
return False
recent = self._history[-need_n:]
if any(s is False for _, _, s in recent):
return False
ws = [w for _, w, _ in recent]
return (max(ws) - min(ws)) <= delta_kg
def scale_stable(self, need_n=2, spread_kg=0.02, max_age_ms=800):
"""秤自己报的稳定(帧里带 ST)——现场放稳后秤会立刻置 ST。
要求:最近 need_n 帧全是 ST、这几帧极差 <= spread_kg、且最后一帧够新。
三个条件缺一不可:
· 不全 ST → 秤自己说还在晃,不听;
· 极差超容差 → 人还在慢慢加货,别提前起流程;
· 帧太旧 → 秤可能掉线,别拿老数据当稳定。
只读秤/不吐 ST 的秤永远返回 False,自动退回按时间窗口判稳。
"""
with self._lock:
if len(self._history) < need_n:
return False
recent = self._history[-need_n:]
if any(s is not True for _, _, s in recent):
return False
age = (time.monotonic() - recent[-1][0]) * 1000.0
if age > max_age_ms:
return False
ws = [w for _, w, _ in recent]
return (max(ws) - min(ws)) <= max(0.001, float(spread_kg))
def flat_for(self, seconds, tol_kg, max_age_ms=800):
"""最近 seconds 秒内重量有没有净变化(用于「真的放稳了」判断)。
现场教训:便宜秤的 ST 位经常在「手还在往下放/慢慢加货」的瞬间
就闪一下 True,光凭 ST + 两帧极差(200ms)会提前起流程——抓拍
冻结的重量比实际轻一大截(日志:冻结 0.440,复核时已 0.580)。
这里要求整段窗口内极差都在容差内,等于「这一段时间秤没在爬」。
"""
with self._lock:
if not self._history:
return False
now = time.monotonic()
if (now - self._history[-1][0]) * 1000.0 > max_age_ms:
return False
window = [(t, w) for t, w, _ in self._history
if now - t <= seconds]
if len(window) < 3:
return False
# 历史没覆盖满整个窗口(刚启动/刚重连)不算稳
if (now - window[0][0]) < seconds * 0.6:
return False
ws = [w for _, w in window]
return (max(ws) - min(ws)) <= max(0.001, float(tol_kg))
def state(self, cfg_flow=None):
cfg_flow = cfg_flow or {}
min_w = float(cfg_flow.get('min_scale_kg',
self.cfg.get('min_weight_kg', 0.05)))
with self._lock:
gross = round(self.weight - self._zero, 3)
tare = self._tare
w = gross - tare # 净重:提交、判稳、报表全用这个
# 现场 21:36 出现过 -0.010:货刚搬走、零点还没稳住时净重会算成
# 负数。负数不能流到上层 —— 复核会拿它跟冻结重量比,永远“重量
# 还在变化”,流程空转到超时;日志里也会出现 -0.010 这种读数。
# 对外一律给 0(原始值留在 raw 里,去皮/零点排查还能看)。
w_rep = max(0.0, w)
fresh = self.is_fresh(float(cfg_flow.get('frame_stale_ms',
FRAME_STALE_MS)))
return {
'weight': round(w_rep, 3),
'raw': round(w, 3),
'gross': round(gross, 3),
'tare': round(tare, 3),
'zero': round(self._zero, 3),
'present': w_rep >= min_w,
'fresh': fresh,
'connected': self.connected,
'overload': self.overload,
'paused': self._paused,
'error': self.error,
}