Files
windows-fenjian/core/devices.py
T

540 lines
23 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 -*-
"""设备自动识别:摄像头 / 电子秤 / 标签打印机。
现场三台设备都会被换(工位搬迁、备机顶上、线松了换口),让操作员去设置页
一个个点是现场最容易出错的环节。这里把「不认识设备也能自己找对」的判定
集中起来,只做只读探测,**不写配置**,是否采纳由调用方决定。
判定口径
--------
摄像头:只认 USB(沿用 usbcam 的 PnP + DShow 双保险)。多台时优先外接那台
(名字含 Integrated / NB Pro / 内置 的排后),并按名字定位索引 ——
DirectShow 索引会随插拔漂移,名字不会。
电子秤:枚举串口 → 在候选波特率上各读一小段 → 用 parse_frame 数有效帧。
得分 = 有效帧 / 行数,且原始字节可读率要够(波特率错时收到的是乱码)。
串口描述带 蓝牙 / 调制解调器 / 传真 的直接跳过(省时间也防误判)。
耀华 XK3190-A12+E 现场实测是 1200-8-N-1,所以 1200 排第一个试。
打印机:型号/驱动名命中标签机关键词(TSC / Zebra / XP- / 佳博 / 汉印 / 芯烨…)
优先;虚拟打印机(OneNote / PDF / XPS / Fax)一律排除;都没有时退到
Windows 默认打印机(只要不是虚拟的)。
"""
import time
from core.scale.reader import list_serial_ports, parse_frame
# ---------------------------------------------------------------- 通用
def _norm(s):
return ''.join(str(s or '').lower().split())
# ---------------------------------------------------------------- 摄像头
# 现场优先外接摄像头(内置 720P 只能凑合看画面)
_INTEGRATED = ('integrated', '内置', 'nb pro', '笔记本', 'laptop',
'front camera', '前置', 'ir camera', 'windows hello')
_HIGH_END = ('4k', '2k', '1080', 'autofocus', 'af', 'usb camera', 'webcam')
def detect_camera(cfg, deep=False):
"""识别摄像头。
deep=False 只读设备名与 USB 判定(毫秒级,不动摄像头);
deep=True 才真的开一次设备验证有画面(设置页「自动识别」用,几秒)。
"""
out = {'ok': False, 'index': None, 'name': '', 'backend': '',
'width': 0, 'height': 0, 'note': '', 'candidates': []}
if ((cfg or {}).get('camera') or {}).get('simulate'):
out['note'] = '模拟画面(配置里开着 camera.simulate)'
return out
try:
from core.evidence import usbcam
except Exception as e: # noqa: BLE001
out['note'] = '摄像头模块不可用:%s' % e
return out
idxs, info = usbcam.usb_indices(force=True)
if idxs is None:
out['note'] = '读不到摄像头设备列表(pygrabber 不可用),无法判定 USB'
return out
if not idxs:
out['note'] = ('没发现 USB 摄像头(%d 个非 USB 设备已忽略)'
% len(info.get('ignored') or []))
return out
conf = (cfg or {}).get('camera', {}) or {}
cur_name = str(conf.get('name') or '')
# 候选:名字 + 索引 + 打分(外接优先,高分屏优先)
cands = []
for i in idxs:
nm = usbcam.device_name(i) or ''
low = nm.lower()
score = 0
if not any(k in low for k in _INTEGRATED):
score += 100
if any(k in low for k in _HIGH_END):
score += 20
if cur_name and _norm(nm) == _norm(cur_name):
score += 50 # 上次用的就是它,别乱换
cands.append({'index': i, 'name': nm, 'score': score})
cands.sort(key=lambda d: (-d['score'], d['index']))
out['candidates'] = cands
pick = cands[0]
if cur_name:
# 配置里记的是名字:只要这台还在,就继续用它(不因插拔漂移而换设备)
ri = usbcam.resolve_name(cur_name)
if ri is not None and ri in idxs:
pick = next(d for d in cands if d['index'] == ri)
out['index'] = pick['index']
out['name'] = pick['name']
out['backend'] = str(conf.get('backend') or 'dshow')
out['width'] = int(conf.get('width') or 0)
out['height'] = int(conf.get('height') or 0)
out['ok'] = True
if deep:
try:
from core.evidence import frames
diag = {}
hit = frames.discover_devices(
pick['index'], out['width'] or 1280, out['height'] or 720,
timeout=24.0, indices=[pick['index']], diag=diag)
if not hit:
out['ok'] = False
hint = frames.diag_hint(diag, [pick['index']])
if not hint:
hint = ('%s 打不开(探测无响应,检查设备管理器与 USB 线)'
% (pick['name'] or '%d 号' % pick['index']))
own = frames.holder_hint()
if own:
hint += ';' + own
out['note'] = hint
else:
h = hit[0]
out['backend'] = h.get('backend', out['backend'])
# 以实测为准:配置里写的档位这台设备未必支持
out['width'] = int(h.get('width') or out['width'] or 0)
out['height'] = int(h.get('height') or out['height'] or 0)
out['measured'] = True
except Exception as e: # noqa: BLE001
out['ok'] = False
out['note'] = '验证画面失败:%s' % e
if not out['note'] and len(cands) > 1:
out['note'] = '共 %d 台 USB 摄像头,已选 %s' % (
len(cands), pick['name'] or '%d 号' % pick['index'])
return out
# ---------------------------------------------------------------- 电子秤
# 耀华 XK3190-A12+E = 1200;其它国产秤常见 9600/4800;老秤 600/2400
BAUDS = (1200, 9600, 4800, 2400, 19200, 600)
_SKIP_PORT_HINTS = ('蓝牙', 'bluetooth', '调制解调器', 'modem', '传真', 'fax',
'红外', 'infrared')
def _printable_ratio(buf):
if not buf:
return 0.0
good = sum(1 for c in buf if 32 <= c < 127 or c in (10, 13))
return good / float(len(buf))
def probe_port(port, bauds=BAUDS, per_baud=0.8, deadline=None):
"""在一个串口上试各波特率,返回 (best_baud, score, frames, note)。
score = 可解析帧 / 行数,且要求原始字节可读率 ≥ 0.85(波特率错是乱码)。
"""
best = (None, 0.0, 0, '')
try:
import serial
except Exception as e: # noqa: BLE001
return None, 0.0, 0, '未安装 pyserial:%s' % e
note = ''
for baud in bauds:
if deadline and time.monotonic() > deadline:
note = note or '超时,剩余波特率未试'
break
sp = None
try:
sp = serial.Serial(port, int(baud), bytesize=8, parity='N',
stopbits=1, timeout=0.15)
sp.reset_input_buffer()
buf = b''
t0 = time.monotonic()
while time.monotonic() - t0 < per_baud:
buf += sp.read(512)
if not buf:
continue
ratio = _printable_ratio(buf)
if ratio < 0.85:
note = '收到乱码(波特率不对或线序有问题),换个速率再试'
continue
lines = [ln for ln in buf.decode('gbk', 'ignore')
.replace('\r', '\n').split('\n') if ln.strip()]
if not lines:
continue
good = 0
for ln in lines:
w, _st, _ov = parse_frame(ln.strip(), 'auto', None)
if w is not None:
good += 1
score = good / float(len(lines))
if good and score > best[1]:
best = (int(baud), score, good, '')
if score >= 0.6 and good >= 3:
break # 已经是「连续正常帧」,不用再试
except Exception as e: # noqa: BLE001
msg = str(e)
low = msg.lower()
if 'permission' in low or 'access is denied' in low or '拒绝访问' in msg:
return None, 0.0, 0, '%s 被其它程序占用(先关掉那个程序)' % port
if 'could not open' in low or 'filenotfound' in low:
return None, 0.0, 0, '%s 打不开(查线/驱动)' % port
note = msg
finally:
if sp is not None:
try:
sp.close()
except Exception:
pass
return best[0], best[1], best[2], (best[3] or note)
def detect_scale(cfg, bauds=BAUDS, budget=12.0, stop=None, start=None,
paused_s=1.2, is_connected=None):
"""识别电子秤:返回 {'ok','port','baudrate','note','candidates','tried'}。
· 秤正在出数(is_connected)→ 直接沿用当前串口,一点都不打扰
· 否则先试配置里的串口(命中就 1 秒内返回,正常开机不拖慢)
· 再按「描述像 USB 转串口」排序列出其它串口逐个试
· stop()/start() 用来临时放开正在被 ScaleReader 占用的串口
"""
out = {'ok': False, 'port': '', 'baudrate': 0, 'note': '',
'candidates': [], 'tried': []}
conf = (cfg or {}).get('scale', {}) or {}
if conf.get('simulate'):
out['note'] = '模拟秤(配置里开着 scale.simulate)'
return out
cur_port = str(conf.get('port') or '').upper()
cur_baud = int(conf.get('baudrate') or 0)
if is_connected is not None:
try:
if is_connected():
out.update(ok=True, port=conf.get('port', ''),
baudrate=cur_baud,
note='秤正在出数,沿用当前串口 %s @ %s'
% (conf.get('port', ''), cur_baud))
return out
except Exception:
pass
ports = [p for p in (list_serial_ports() or [])
if not any(h in (p.get('description') or '').lower()
for h in _SKIP_PORT_HINTS)]
if not ports:
out['note'] = '没发现串口(查 RS232 线 / USB 转串口驱动是否装好)'
return out
out['candidates'] = ports
# 排顺序:配置口 → 描述像 USB/串口 → 其余
def prio(p):
d = (p.get('description') or '').lower()
s = 0
if p['port'].upper() == cur_port:
s -= 100
if 'usb' in d or 'ch340' in d or 'cp210' in d or 'ftdi' in d or '串口' in d:
s -= 10
return s
order = sorted(ports, key=prio)
deadline = time.monotonic() + float(budget)
held = False
best = None
try:
for i, p in enumerate(order):
# 探测配置口时先让 ScaleReader 松手,否则必然「被占用」
if stop and not held and p['port'].upper() == cur_port:
try:
stop()
except Exception:
pass
held = True
time.sleep(paused_s)
seq = list(bauds)
if p['port'].upper() == cur_port and cur_baud in seq:
seq.remove(cur_baud)
seq.insert(0, cur_baud) # 配置的波特率先试
baud, score, frames, note = probe_port(
p['port'], seq, per_baud=0.8, deadline=deadline)
out['tried'].append({'port': p['port'], 'baud': baud,
'score': round(score, 2), 'frames': frames})
if baud and (best is None or score > best[2]):
best = (p['port'], baud, score, frames, p.get('description', ''))
if score >= 0.6 and frames >= 3:
break
if note and not out['note']:
out['note'] = note
if time.monotonic() > deadline and i < len(order) - 1:
out['note'] = out['note'] or '时间到,只试了前 %d 个串口' % (i + 1)
break
finally:
if held and start:
try:
start()
except Exception:
pass
if best:
out.update(ok=True, port=best[0], baudrate=best[1])
out['note'] = '%s%s 有正常重量帧(%d 帧)' % (
best[0], ('(%s)' % best[4]) if best[4] else '', best[3])
if best[2] < 0.6:
out['note'] += ',但帧格式不规整,建议在高级设置里核对帧格式'
elif not out['note']:
out['note'] = ('串口都在,但读不到重量:秤是否开机?通讯方式是否'
'「连续发送」?线是否插在秤的 RS232 口(不是 USB 打印口)')
return out
# ---------------------------------------------------------------- 打印机
# 标签机关键词:命中越多越优先
_LABEL_HINTS = (
'标签', 'label', 'barcode', '条码', 'tsc', 'ttp-', 'zebra', 'zpl',
'godex', '科诚', 'argox', '立象', 'postek', '博思得', 'sato', 'gprinter',
'佳博', 'xprinter', '芯烨', 'hprt', '汉印', 'deli', '得力', 'qirui',
'启锐', 'xp-', 'gp-', 'sp-', 'tspl', '热敏', 'thermal',
)
# 虚拟/办公打印机:绝不当作标签机
_VIRTUAL_HINTS = (
'onenote', 'print to pdf', 'microsoft print', 'xps', 'fax', '传真',
'virtual', '虚拟', 'pdf24', 'adobe pdf', 'cute pdf', '共享', 'shared',
'send to', '发送至',
)
def list_printers_detail():
"""[{name, driver, port, is_default}];拿不到驱动名时留空。"""
try:
import win32print
except Exception:
return []
out = []
try:
default = ''
try:
default = win32print.GetDefaultPrinter() or ''
except Exception:
default = ''
flags = (win32print.PRINTER_ENUM_LOCAL |
win32print.PRINTER_ENUM_CONNECTIONS)
for info in win32print.EnumPrinters(flags, None, 2):
name = info.get('pPrinterName') if isinstance(info, dict) else ''
if not name:
continue
out.append({'name': name,
'driver': str(info.get('pDriverName') or ''),
'port': str(info.get('pPortName') or ''),
'is_default': (name == default)})
except Exception:
return out
return out
def _printer_score(p):
text = ((p.get('name') or '') + ' ' + (p.get('driver') or '')).lower()
if any(h in text for h in _VIRTUAL_HINTS):
return -1000
score = 0
for h in _LABEL_HINTS:
if h in text:
score += 30
if p.get('is_default'):
score += 8
port = (p.get('port') or '').upper()
if port.startswith(('USB', 'COM')):
score += 12
elif port.startswith(('IP_', 'WSD', '\\\\')):
score += 2
return score
def detect_printer(cfg):
"""识别标签打印机:返回 {'ok','name','driver','note','candidates'}"""
out = {'ok': False, 'name': '', 'driver': '', 'note': '',
'candidates': []}
if ((cfg or {}).get('printer') or {}).get('enabled') is False:
out['note'] = '打印已停用(启用后再识别)'
return out
items = list_printers_detail()
if not items:
out['note'] = '没发现打印机(查 USB / 驱动是否装好)'
return out
scored = []
for p in items:
s = _printer_score(p)
scored.append(dict(p, score=s))
scored.sort(key=lambda d: (-d['score'], d['name']))
out['candidates'] = scored
conf = (cfg or {}).get('printer', {}) or {}
cur = str(conf.get('printer_name') or '')
cur_row = next((p for p in scored if p['name'] == cur), None)
best_label = next((p for p in scored if p['score'] >= 30), None)
# 现场已经手工选过某台,且它不是虚拟打印机、也没认出更像的标签机 → 沿用
if cur_row is not None and cur_row['score'] > -1000:
if best_label is None or cur_row['score'] >= best_label['score']:
out.update(ok=True, name=cur_row['name'], driver=cur_row['driver'])
out['note'] = '沿用已选的打印机'
return out
best = best_label or scored[0]
if best['score'] <= -1000:
out['note'] = '只找到虚拟打印机(OneNote/PDF/XPS),接上标签机再识别'
return out
out.update(ok=True, name=best['name'], driver=best['driver'])
if best['score'] >= 30:
out['note'] = '按型号判定为标签打印机'
elif best['is_default']:
out['note'] = '未认出标签机型号,暂用系统默认打印机'
else:
out['note'] = '未认出标签机型号,暂用第一台非虚拟打印机'
return out
# ---------------------------------------------------------------- 汇总
def detect_all(cfg, deep_camera=False, stop=None, start=None, on_step=None,
is_connected=None):
"""一次识别三台设备。on_step(kind, result) 用于界面实时回显。"""
res = {}
for kind, fn in (('printer', lambda: detect_printer(cfg)),
('camera', lambda: detect_camera(cfg, deep=deep_camera)),
('scale', lambda: detect_scale(cfg, stop=stop,
start=start,
is_connected=is_connected))):
try:
r = fn()
except Exception as e: # noqa: BLE001
r = {'ok': False, 'note': '%s 识别出错:%s' % (kind, e)}
res[kind] = r
if on_step:
try:
on_step(kind, r)
except Exception:
pass
return res
def apply_detect(cfg, res, only_when_broken=True):
"""把识别结果写进 cfg(就地修改),返回改动列表 [(设备, 旧, 新)]。
only_when_broken=True 时,只在「原来那台用不了」时才改,避免每次开机都
覆盖现场手工选过的设备(比如故意选了另一台打印机打大标签)。
"""
changes = []
r = res.get('camera') or {}
# 分辨率被设备降档(配置写 2560×1440、实际只给 1280×720)是客观事实,
# 不管 only_when_broken 都该写回去,否则每次启动都要先撞一次墙
if r.get('ok') and r.get('measured') and r.get('width'):
cam = cfg.setdefault('camera', {})
if not cam.get('simulate'):
ow = int(cam.get('width') or 0)
oh = int(cam.get('height') or 0)
nw, nh = int(r['width']), int(r.get('height') or 0)
if ow > 0 and oh > 0 and (ow, oh) != (nw, nh):
cam['width'], cam['height'] = nw, nh
changes.append(('摄像头分辨率', '%dx%d' % (ow, oh),
'%dx%d' % (nw, nh)))
# 模拟模式是人为开的(演示/无设备),不去覆盖它
if r.get('ok') and r.get('name') and not cfg.get('camera', {}).get('simulate'):
cam = cfg.setdefault('camera', {})
old = str(cam.get('name') or '')
old_ok = False
if old:
try:
from core.evidence import usbcam
old_ok = usbcam.resolve_name(old) is not None
except Exception:
old_ok = False
if (not only_when_broken) or (not old_ok):
if old != r['name']:
cam['name'] = r['name']
changes.append(('摄像头', old or '(未设置)', r['name']))
if r.get('index') is not None:
cam['index'] = int(r['index'])
if r.get('backend'):
cam['backend'] = r['backend']
cam['usb_only'] = True
r = res.get('scale') or {}
if r.get('ok') and r.get('port') and not cfg.get('scale', {}).get('simulate'):
sc = cfg.setdefault('scale', {})
old_port = str(sc.get('port') or '')
old_baud = int(sc.get('baudrate') or 0)
# 「原来那台还能用」由 detect_scale 自己判:它先试配置口,命中就返回
# 配置口,不会给出别的口,所以这里直接采纳即可
if old_port.upper() != r['port'].upper() or old_baud != int(r['baudrate']):
sc['port'] = r['port']
sc['baudrate'] = int(r['baudrate'])
sc['simulate'] = False
changes.append(('电子秤',
'%s @ %s' % (old_port or '未设置', old_baud or '?'),
'%s @ %s' % (r['port'], r['baudrate'])))
r = res.get('printer') or {}
# 打印被手工停用时不擅自打开(现场可能故意只称重不打标签)
if r.get('ok') and r.get('name') and \
cfg.get('printer', {}).get('enabled', True) is not False:
pr = cfg.setdefault('printer', {})
old = str(pr.get('printer_name') or '')
cands = r.get('candidates') or []
old_row = next((p for p in cands if p['name'] == old), None)
old_ok = old_row is not None and old_row['score'] > -1000
label_found = any(p['score'] >= 30 for p in cands)
# 该换的三种情况:原来那台没了 / 原来是虚拟打印机 / 认出标签机了
# 而原来只是台普通办公打印机(打标签会把 50×50 的版面打到 A4 上)
should = (not old_ok) or (label_found and
(old_row is None or old_row['score'] < 30))
if (not only_when_broken) or should:
if old != r['name']:
pr['printer_name'] = r['name']
pr['enabled'] = True
changes.append(('标签打印机', old or '(未设置)', r['name']))
# 配置里那台打印机在本机根本不存在(换机器/换电脑后配置被带过来最常见,
# 或者标签机拔了):留着它只会让每件货都报 (1801, 打印机名无效)。
# 枚举到了打印机列表才判断,避免「一台都没枚举出来」时误清空。
pr = cfg.setdefault('printer', {})
cur_name = str(pr.get('printer_name') or '')
cands_all = (res.get('printer') or {}).get('candidates') or []
if cur_name and cands_all and \
not any(p.get('name') == cur_name for p in cands_all):
pr['printer_name'] = ''
changes.append(('标签打印机', cur_name,
'(本机无此打印机,已清空,接上标签机后重新识别)'))
return changes
def summary_text(res):
"""一行话总结识别结果(日志/状态条用),未识别时说清为什么"""
def bit(label, r, ok_text):
r = r or {}
if r.get('ok'):
return '%s %s' % (label, ok_text(r))
note = str(r.get('note') or '').strip()
if len(note) > 40: # 太短会把「为什么没识别」的关键信息截掉
note = note[:40] + '…'
return '%s 未识别%s' % (label, ('(%s)' % note) if note else '')
return ' · '.join([
bit('摄像头', res.get('camera'),
lambda r: r.get('name') or ('%s 号' % r.get('index'))),
bit('秤', res.get('scale'),
lambda r: '%s@%s' % (r.get('port'), r.get('baudrate'))),
bit('打印机', res.get('printer'), lambda r: r.get('name') or ''),
])