summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorjaseg <git@jaseg.net>2018-11-06 21:17:29 +0900
committerjaseg <git@jaseg.net>2018-11-06 21:17:29 +0900
commit51e08c3c89c90fdbc27cc8aca7b5c6f569dbb258 (patch)
tree9233c09dad4351978ea183222062ae87b7a10f0b
parent985710d517e38a93be7658d4e4e8967c356a4ef9 (diff)
downloadsecure-hid-51e08c3c89c90fdbc27cc8aca7b5c6f569dbb258.tar.gz
secure-hid-51e08c3c89c90fdbc27cc8aca7b5c6f569dbb258.tar.bz2
secure-hid-51e08c3c89c90fdbc27cc8aca7b5c6f569dbb258.zip
Add nice hexdumpy serial utility
-rwxr-xr-xhexcom.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/hexcom.py b/hexcom.py
new file mode 100755
index 0000000..c9f290b
--- /dev/null
+++ b/hexcom.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python3
+
+import time
+import string
+
+def _print_line(write, ts, line, width=16):
+ h,m,s,ms = int(ts//3600), int((ts//60)%60), int(ts%60), int((ts%1.0) * 1000)
+ timestamp = f'{h: 3d}:{m:02d}:{s:02d}:{ms:03d}'
+ line = list(line) + [None]*(width-len(line))
+ hexcol = '\033[94m'
+ col = lambda b, s: s if b != 0 else f'\033[91m{s}{hexcol}'
+ hexfmt = ' '.join(
+ ' '.join(col(b, f'{b:02x}') if b is not None else ' ' for b in line[i*8:i*8+8])
+ for i in range(1 + (len(line)-1)//8))
+ asciifmt = ''.join(chr(c) if c is not None and chr(c) in string.printable else '.' for c in line)
+ write(f'\033[38;5;244m{timestamp} {hexcol}{hexfmt} \033[38;5;244m|\033[92m{asciifmt}\033[38;5;244m|\033[0m', flush=True, end='')
+
+def hexcom(write, ser, width=16):
+ current_line = b''
+ start = time.time()
+ while ser.is_open:
+ data = ser.read_all() # non-blocking, flushes buffer
+ if not data:
+ data = ser.read(1) # blocking
+ ts = time.time()
+
+ current_line += data
+ write('\033[2K\r', end='')
+ while len(current_line) > width:
+ chunk, current_line = current_line[:width], current_line[width:]
+ _print_line(write, ts-start, chunk, width=width)
+ write()
+ _print_line(write, ts-start, current_line, width=width)
+
+if __name__ == '__main__':
+ import argparse
+ import serial
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument('serial')
+ parser.add_argument('baudrate')
+ parser.add_argument('-w', '--width', type=int, default=16, help='Number of bytes to display in one line')
+ args = parser.parse_args()
+
+ ser = serial.Serial(args.serial, args.baudrate)
+ hexcom(print, ser, width=args.width)