cosmo/terminal/tools/key_watch.py

44 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""按键排查:打开串口 -> 打印 XL9555 寄存器 -> 持续把设备日志带时间戳落盘。
依次按 KEY0/KEY1/KEY2/KEY3/BOOT,每颗停一秒,日志里就能看到每颗键触发的是哪一位。
用法: key_watch.py [监听秒数=240] [日志=/tmp/keywatch.log]
"""
import serial, sys, time
import glob, os
#: 换过 USB 口(CH340 -> 板载 USB-CDC)就别让脚本抓瞎:COSMO_PORT 优先,否则挑一个在的
def _pick_port():
env = os.environ.get('COSMO_PORT')
if env: return env
for pat in ('/dev/cu.usbserial*', '/dev/cu.usbmodem*'):
m = sorted(glob.glob(pat))
if m: return m[0]
return '/dev/cu.usbserial-210'
PORT = _pick_port()
BAUD = 115200
dur = float(sys.argv[1]) if len(sys.argv) > 1 else 240
path = sys.argv[2] if len(sys.argv) > 2 else '/tmp/keywatch.log'
t0 = time.time()
log = open(path, 'a', buffering=1)
s = serial.Serial(PORT, BAUD, timeout=0.2, write_timeout=5)
time.sleep(1.0)
for c in ('xlreg', 'keys'):
s.write(c.encode() + b'\r\n')
s.flush()
log.write('\n===== key_watch %s 请按 KEY0 KEY1 KEY2 KEY3 BOOT,每颗停一秒 =====\n' % time.strftime('%H:%M:%S'))
buf = b''
while time.time() - t0 < dur:
d = s.read(4096)
if not d:
continue
buf += d
while b'\n' in buf:
line, buf = buf.split(b'\n', 1)
text = line.decode('utf8', 'replace').rstrip()
if text:
log.write('%7.2f %s\n' % (time.time() - t0, text))
s.close()
log.write('===== key_watch end =====\n')