Files

192 lines
8.2 KiB
Python
Raw Permalink 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 / COM 口时先跑这个)。
用途:确认「线接对了、参数对了、秤在吐数、格式能认」四件事,
再回主程序设置页点选串口,避免在黑屏里猜。
用法(在项目根目录):
python tools/scale_probe.py --list
列出本机所有 COM 口(含芯片名,判断 USB 转串口有没有装好)
python tools/scale_probe.py --port COM3
按 9600/8/N/1 读 15 秒,逐帧打印原始字节 + 解析结果
python tools/scale_probe.py --port COM3 --baud 4800 --parity E --stopbits 2
改串口参数(必须与秤的出厂设置一致)
python tools/scale_probe.py --port COM3 --send "hex:1B 54 0D" --send-at 3
读取过程中第 3 秒给秤发一次去皮命令,看它有没有反应
python tools/scale_probe.py --port COM3 --raw
只打原始字节(不解析),用于判断是不是二进制协议
注意:主程序运行时会占着串口,先关掉主程序再测,否则报"拒绝访问"。
"""
import argparse
import sys
import time
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
try:
import serial
from serial.tools import list_ports
except ImportError:
print('缺少 pyserial:pip install pyserial')
sys.exit(1)
from core.scale.reader import parse_frame # noqa: E402
def do_list():
ports = list(list_ports.comports())
if not ports:
print('没有发现任何串口。\n'
'· 用 USB 转 RS232 线时,先看设备管理器 → 端口(COM 和 LPT) 有没有'
'「USB-SERIAL CH340 / FT232 / PL2303」,没有就装驱动\n'
'· 主板原生 COM 口被 BIOS 关掉时也不会出现,进 BIOS 打开 Serial Port')
return
print('发现 %d 个串口:' % len(ports))
for p in ports:
print(' %-6s %-42s %s' % (p.device, p.description or '',
getattr(p, 'hwid', '') or ''))
print('\n接秤就选列表里那个 COMx;如果同时有多个,拔掉秤再看少哪个。')
def main():
ap = argparse.ArgumentParser(add_help=True)
ap.add_argument('--list', action='store_true', help='只列串口')
ap.add_argument('--port', default='COM3')
ap.add_argument('--baud', type=int, default=9600)
ap.add_argument('--bytesize', type=int, default=8)
ap.add_argument('--parity', default='N', choices=['N', 'E', 'O', 'M', 'S'])
ap.add_argument('--stopbits', type=float, default=1)
ap.add_argument('--secs', type=float, default=15.0, help='读取时长')
ap.add_argument('--unit', default='auto', choices=['auto', 'kg', 'g', 'lb'],
help='帧里没单位后缀时按这个解释')
ap.add_argument('--pattern', default='',
help='取重量的正则(第1个分组),帧里有流水号时用')
ap.add_argument('--raw', action='store_true', help='只打原始字节')
ap.add_argument('--send', action='append', default=[],
help='要发给秤的命令,可多次;ASCII 直接写,或 hex:1B 54 0D')
ap.add_argument('--send-at', type=float, default=3.0,
help='第几秒发命令(秒)')
a = ap.parse_args()
if a.list:
do_list()
return
print('打开 %s @ %d/%d/%s/%g …' % (a.port, a.baud, a.bytesize,
a.parity, a.stopbits))
try:
ser = serial.Serial(port=a.port, baudrate=a.baud,
bytesize=a.bytesize, parity=a.parity,
stopbits=a.stopbits, timeout=0.3)
except Exception as e: # noqa: BLE001
print('打不开:%s\n'
'· \"拒绝访问/占用\" → 关掉主程序、串口调试助手、厂家上位机\n'
'· \"找不到\" → 用 --list 看实际 COM 号\n'
'· 参数不对不会打不开,只会读到乱码' % e)
return
buf = b''
frames = 0
parsed_ok = 0
stable_flag = 0
overload = 0
t0 = time.time()
sent = False
last_print = 0.0
print('读取 %.0f 秒,请把货放上秤(或空秤也行)…\n' % a.secs)
try:
while time.time() - t0 < a.secs:
if a.send and not sent and time.time() - t0 >= a.send_at:
sent = True
for s in a.send:
data = (bytes.fromhex(s[4:].replace(' ', ''))
if s.lower().startswith('hex:') else s.encode())
ser.write(data)
ser.flush()
print(' >> 发送 %s (%s)' % (data.hex(' ').upper(),
repr(s)))
chunk = ser.read(128)
if not chunk:
continue
if a.raw:
if time.time() - last_print > 0.2:
last_print = time.time()
print(' raw %s | %s' % (
chunk.hex(' ').upper(),
chunk.decode('gbk', 'replace').replace('\r', '\\r')
.replace('\n', '\\n')))
continue
buf += chunk
while b'\r' in buf or b'\n' in buf:
idxs = [i for i in (buf.find(b'\r'), buf.find(b'\n')) if i >= 0]
idx = min(idxs)
raw = buf[:idx]
buf = buf[idx + 1:]
if not raw.strip():
continue
frames += 1
try:
line = raw.decode('ascii')
except UnicodeDecodeError:
line = raw.decode('gbk', 'ignore')
w, stable, oL = parse_frame(line, a.unit,
a.pattern or None)
if oL:
overload += 1
if w is not None:
parsed_ok += 1
if stable is True:
stable_flag += 1
print(' [%05.1fs] %-28r → %s' % (
time.time() - t0, line,
('OL 超载' if oL else
('%.3f kg %s' % (w, {True: '稳定(ST)', False: '不稳(US)',
None: '无状态位'}[stable])
if w is not None else '未识别'))))
except KeyboardInterrupt:
print('\n手动中断')
finally:
ser.close()
dur = max(0.1, time.time() - t0)
print('\n---- 结论 ----')
print('时长 %.1fs,收到 %d 帧(约 %.1f 帧/秒),可解析 %d 帧'
% (dur, frames, frames / dur, parsed_ok))
if frames == 0:
print('✘ 一帧都没收到,按顺序排查:')
print(' 1) 秤要开「连续发送/连续输出」模式(有些秤默认只应答);')
print(' 2) 线:秤是 DB9 母口(DCE),PC 若是原生公口可直连;'
'两头都是母口/都是 DTE 时必须用交叉线(2↔3 对调、5 是地);')
print(' 3) 波特率先试 9600,再试 4800 / 19200 / 2400;')
print(' 4) 用 --raw 看有没有原始字节(有字节但解析不出来 = 协议问题)。')
elif parsed_ok == 0:
print('△ 有数据但解析不出重量,把上面打印的原始帧发给开发,'
'按实际格式加一条解析规则(2 分钟的事)。')
else:
print('✔ 解析正常。回主程序:设置页 → 电子秤 → 扫描串口 → 选 %s'
% a.port)
print(' 并把 config.json 的 scale 改成:port=%s baudrate=%d '
'parity=%s bytesize=%d stopbits=%g,simulate=false'
% (a.port, a.baud, a.parity, a.bytesize, a.stopbits))
if stable_flag:
print(' ✔ 帧里带 ST/US 稳定位,判稳会用它(不用等满 5 帧)')
else:
print(' · 帧里没有稳定位,靠「连续 5 帧波动 ≤20g」判稳'
'(stable_tolerance_kg 可调)')
if overload:
print(' ✔ 能识别 OL 超载')
if not a.send:
print(' · 还没试过控制(去皮/置零):用 --send "hex:1B 54 0D" '
'之类的命令试;成功后再填 config 的 scale.tare_cmd')
if __name__ == '__main__':
main()