blob: f8449e22aabcc190940e99cc4eb865ab69877f8d [file] [log] [blame]
Chris Liechti3e02f702015-12-16 23:06:04 +01001#! python
2#
3# This is a codec to create and decode hexdumps with spaces between characters. used by miniterm.
4#
5# This file is part of pySerial. https://github.com/pyserial/pyserial
Chris Liechti4e34c4c2016-02-19 23:54:14 +01006# (C) 2015-2016 Chris Liechti <cliechti@gmx.net>
Chris Liechti3e02f702015-12-16 23:06:04 +01007#
8# SPDX-License-Identifier: BSD-3-Clause
Chris Liechtic0c660a2015-08-25 00:55:51 +02009"""\
10Python 'hex' Codec - 2-digit hex with spaces content transfer encoding.
Chris Liechti4e34c4c2016-02-19 23:54:14 +010011
12Encode and decode may be a bit missleading at first sight...
13
14The textual representation is a hex dump: e.g. "40 41"
15The "encoded" data of this is the binary form, e.g. b"@A"
16
17Therefore decoding is binary to text and thus converting binary data to hex dump.
18
Chris Liechtic0c660a2015-08-25 00:55:51 +020019"""
20
21import codecs
22import serial
23
24HEXDIGITS = '0123456789ABCDEF'
25
Chris Liechtic0c660a2015-08-25 00:55:51 +020026
Chris Liechti92df95a2016-02-09 23:30:37 +010027# Codec APIs
Chris Liechti033f17c2015-08-30 21:28:04 +020028
Chris Liechti4e34c4c2016-02-19 23:54:14 +010029def hex_encode(data, errors='strict'):
30 """'40 41 42' -> '@ab'"""
31 return (serial.to_bytes([int(h, 16) for h in data.split()]), len(data))
Chris Liechtic0c660a2015-08-25 00:55:51 +020032
Chris Liechti033f17c2015-08-30 21:28:04 +020033
Chris Liechti4e34c4c2016-02-19 23:54:14 +010034def hex_decode(data, errors='strict'):
35 """'@ab' -> '40 41 42'"""
36 return (''.join('{:02X} '.format(b) for b in data), len(data))
Chris Liechtic0c660a2015-08-25 00:55:51 +020037
Chris Liechti033f17c2015-08-30 21:28:04 +020038
Chris Liechtic0c660a2015-08-25 00:55:51 +020039class Codec(codecs.Codec):
Chris Liechti4e34c4c2016-02-19 23:54:14 +010040 def encode(self, data, errors='strict'):
41 """'40 41 42' -> '@ab'"""
42 return serial.to_bytes([int(h, 16) for h in data.split()])
Chris Liechti033f17c2015-08-30 21:28:04 +020043
Chris Liechti4e34c4c2016-02-19 23:54:14 +010044 def decode(self, data, errors='strict'):
45 """'@ab' -> '40 41 42'"""
46 return ''.join('{:02X} '.format(b) for b in data)
Chris Liechtic0c660a2015-08-25 00:55:51 +020047
Chris Liechti033f17c2015-08-30 21:28:04 +020048
Chris Liechtic0c660a2015-08-25 00:55:51 +020049class IncrementalEncoder(codecs.IncrementalEncoder):
Chris Liechti4e34c4c2016-02-19 23:54:14 +010050 """Incremental hex encoder"""
Chris Liechtic0c660a2015-08-25 00:55:51 +020051
52 def __init__(self, errors='strict'):
53 self.errors = errors
54 self.state = 0
55
56 def reset(self):
57 self.state = 0
58
59 def getstate(self):
60 return self.state
61
62 def setstate(self, state):
63 self.state = state
64
Chris Liechti4e34c4c2016-02-19 23:54:14 +010065 def encode(self, data, final=False):
66 """\
67 Incremental encode, keep track of digits and emit a byte when a pair
68 of hex digits is found. The space is optional unless the error
69 handling is defined to be 'strict'.
70 """
Chris Liechtic0c660a2015-08-25 00:55:51 +020071 state = self.state
72 encoded = []
Chris Liechti4e34c4c2016-02-19 23:54:14 +010073 for c in data.upper():
Chris Liechtic0c660a2015-08-25 00:55:51 +020074 if c in HEXDIGITS:
75 z = HEXDIGITS.index(c)
76 if state:
77 encoded.append(z + (state & 0xf0))
78 state = 0
79 else:
80 state = 0x100 + (z << 4)
81 elif c == ' ': # allow spaces to separate values
82 if state and self.errors == 'strict':
83 raise UnicodeError('odd number of hex digits')
84 state = 0
85 else:
86 if self.errors == 'strict':
87 raise UnicodeError('non-hex digit found: %r' % c)
88 self.state = state
89 return serial.to_bytes(encoded)
90
Chris Liechti033f17c2015-08-30 21:28:04 +020091
Chris Liechtic0c660a2015-08-25 00:55:51 +020092class IncrementalDecoder(codecs.IncrementalDecoder):
Chris Liechti4e34c4c2016-02-19 23:54:14 +010093 """Incremental decoder"""
94 def decode(self, data, final=False):
95 return ''.join('{:02X} '.format(b) for b in data)
Chris Liechtic0c660a2015-08-25 00:55:51 +020096
Chris Liechti033f17c2015-08-30 21:28:04 +020097
Chris Liechtic0c660a2015-08-25 00:55:51 +020098class StreamWriter(Codec, codecs.StreamWriter):
Chris Liechti4e34c4c2016-02-19 23:54:14 +010099 """Combination of hexlify codec and StreamWriter"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200100
Chris Liechti033f17c2015-08-30 21:28:04 +0200101
Chris Liechtic0c660a2015-08-25 00:55:51 +0200102class StreamReader(Codec, codecs.StreamReader):
Chris Liechti4e34c4c2016-02-19 23:54:14 +0100103 """Combination of hexlify codec and StreamReader"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200104
Chris Liechtic0c660a2015-08-25 00:55:51 +0200105
Chris Liechtic0c660a2015-08-25 00:55:51 +0200106def getregentry():
Chris Liechti4e34c4c2016-02-19 23:54:14 +0100107 """encodings module API"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200108 return codecs.CodecInfo(
109 name='hexlify',
110 encode=hex_encode,
111 decode=hex_decode,
112 incrementalencoder=IncrementalEncoder,
113 incrementaldecoder=IncrementalDecoder,
114 streamwriter=StreamWriter,
115 streamreader=StreamReader,
116 _is_text_encoding=True,
117 )