167 lines
5.5 KiB
Python
167 lines
5.5 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""电子秤 RS232 串口读取模块
|
||
|
||
支持两种模式:
|
||
- 真实串口:按 config 中的端口/波特率等参数读取,按行解析重量数字
|
||
- 模拟模式:simulate=True,用于无秤调试(界面点"模拟上货"触发一次称重)
|
||
|
||
稳定判定:最近 stable_count 次读数极差 <= stable_tolerance_kg,
|
||
且重量 >= min_weight_kg 视为"有货且稳定"。
|
||
"""
|
||
import re
|
||
import time
|
||
import random
|
||
import threading
|
||
|
||
try:
|
||
import serial
|
||
except ImportError:
|
||
serial = None
|
||
|
||
_NUM_RE = re.compile(r'[-+]?\d+(?:\.\d+)?')
|
||
|
||
|
||
def parse_weight(line):
|
||
"""从一行串口数据中提取重量数值。
|
||
|
||
通用解析适配大多数连续发送型秤(耀华 XK3190、托利多、柯力等
|
||
的常见帧格式里都含一个带符号小数)。若你的秤有特殊帧格式,
|
||
可在 protocol 中指定,后续再扩展专用解析器。
|
||
"""
|
||
if not line:
|
||
return None
|
||
# 常见格式: "=GS+ 12.340kg" / "ST,GS,+ 12.34 kg" / "12.34\r\n"
|
||
m = _NUM_RE.search(line)
|
||
if not m:
|
||
return None
|
||
try:
|
||
return float(m.group())
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
class ScaleReader:
|
||
def __init__(self, cfg):
|
||
self.cfg = cfg.get('scale', {})
|
||
self.weight = 0.0
|
||
self.raw_line = ''
|
||
self.error = None
|
||
self._history = [] # 最近读数,用于稳定判定
|
||
self._lock = threading.Lock()
|
||
self._sim_target = None # 模拟模式目标重量
|
||
self._sim_current = 0.0
|
||
self._running = False
|
||
self._thread = None
|
||
|
||
# ---------- 生命周期 ----------
|
||
def start(self):
|
||
self._running = True
|
||
self._thread = threading.Thread(target=self._loop, daemon=True)
|
||
self._thread.start()
|
||
|
||
def stop(self):
|
||
self._running = False
|
||
|
||
# ---------- 模拟控制 ----------
|
||
def sim_put(self, kg):
|
||
"""模拟模式下:模拟放上一件货物,重量逐渐趋近目标值"""
|
||
self._sim_target = kg
|
||
|
||
def sim_clear(self):
|
||
self._sim_target = None
|
||
self._sim_current = 0.0
|
||
|
||
# ---------- 内部循环 ----------
|
||
def _loop(self):
|
||
if self.cfg.get('simulate'):
|
||
self._sim_loop()
|
||
else:
|
||
self._serial_loop()
|
||
|
||
def _sim_loop(self):
|
||
while self._running:
|
||
target = self._sim_target
|
||
if target is None:
|
||
nxt = 0.0
|
||
else:
|
||
# 向目标重量靠近 + 轻微噪声
|
||
diff = target - self._sim_current
|
||
step = diff * 0.5 + random.uniform(-0.002, 0.002)
|
||
nxt = max(0.0, self._sim_current + step)
|
||
with self._lock:
|
||
self._sim_current = nxt
|
||
self._push(nxt)
|
||
time.sleep(0.2)
|
||
|
||
def _serial_loop(self):
|
||
if serial is None:
|
||
with self._lock:
|
||
self.error = '未安装 pyserial(pip install pyserial)'
|
||
return
|
||
while self._running:
|
||
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.error = None
|
||
buf = b''
|
||
while self._running:
|
||
chunk = ser.read(64)
|
||
if not chunk:
|
||
continue
|
||
buf += chunk
|
||
while b'\n' in buf or b'\r' in buf:
|
||
idx_n, idx_r = buf.find(b'\n'), buf.find(b'\r')
|
||
idxs = [i for i in (idx_n, idx_r) if i >= 0]
|
||
idx = min(idxs)
|
||
line = buf[:idx].decode('gbk', errors='ignore').strip()
|
||
buf = buf[idx + 1:]
|
||
if not line:
|
||
continue
|
||
w = parse_weight(line)
|
||
if w is not None:
|
||
with self._lock:
|
||
self.raw_line = line
|
||
self._push(w)
|
||
except Exception as e:
|
||
with self._lock:
|
||
self.error = str(e)
|
||
if ser:
|
||
try:
|
||
ser.close()
|
||
except Exception:
|
||
pass
|
||
time.sleep(3) # 断线重连间隔
|
||
|
||
def _push(self, w):
|
||
self.weight = w
|
||
self._history.append(w)
|
||
n = int(self.cfg.get('stable_count', 5))
|
||
if len(self._history) > n:
|
||
self._history = self._history[-n:]
|
||
|
||
# ---------- 对外状态 ----------
|
||
def state(self):
|
||
with self._lock:
|
||
tol = float(self.cfg.get('stable_tolerance_kg', 0.02))
|
||
min_w = float(self.cfg.get('min_weight_kg', 0.05))
|
||
present = self.weight >= min_w
|
||
stable = (
|
||
present
|
||
and len(self._history) >= int(self.cfg.get('stable_count', 5))
|
||
and (max(self._history) - min(self._history)) <= tol
|
||
)
|
||
return {
|
||
'weight': round(self.weight, 3),
|
||
'present': present,
|
||
'stable': stable,
|
||
'error': self.error,
|
||
}
|