]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - processor-sdk/performance-audio-sr.git/blob - tools/pyalpha/serial/tools/hexlify_codec.py
Update submodule URLs
[processor-sdk/performance-audio-sr.git] / tools / pyalpha / serial / tools / hexlify_codec.py
1 #! 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
6 # (C) 2015-2016 Chris Liechti <cliechti@gmx.net>
7 #
8 # SPDX-License-Identifier:    BSD-3-Clause
9 """\
10 Python 'hex' Codec - 2-digit hex with spaces content transfer encoding.
12 Encode and decode may be a bit missleading at first sight...
14 The textual representation is a hex dump: e.g. "40 41"
15 The "encoded" data of this is the binary form, e.g. b"@A"
17 Therefore decoding is binary to text and thus converting binary data to hex dump.
19 """
21 import codecs
22 import serial
25 try:
26     unicode
27 except (NameError, AttributeError):
28     unicode = str       # for Python 3, pylint: disable=redefined-builtin,invalid-name
31 HEXDIGITS = '0123456789ABCDEF'
34 # Codec APIs
36 def hex_encode(data, errors='strict'):
37     """'40 41 42' -> b'@ab'"""
38     return (serial.to_bytes([int(h, 16) for h in data.split()]), len(data))
41 def hex_decode(data, errors='strict'):
42     """b'@ab' -> '40 41 42'"""
43     return (unicode(''.join('{:02X} '.format(ord(b)) for b in serial.iterbytes(data))), len(data))
46 class Codec(codecs.Codec):
47     def encode(self, data, errors='strict'):
48         """'40 41 42' -> b'@ab'"""
49         return serial.to_bytes([int(h, 16) for h in data.split()])
51     def decode(self, data, errors='strict'):
52         """b'@ab' -> '40 41 42'"""
53         return unicode(''.join('{:02X} '.format(ord(b)) for b in serial.iterbytes(data)))
56 class IncrementalEncoder(codecs.IncrementalEncoder):
57     """Incremental hex encoder"""
59     def __init__(self, errors='strict'):
60         self.errors = errors
61         self.state = 0
63     def reset(self):
64         self.state = 0
66     def getstate(self):
67         return self.state
69     def setstate(self, state):
70         self.state = state
72     def encode(self, data, final=False):
73         """\
74         Incremental encode, keep track of digits and emit a byte when a pair
75         of hex digits is found. The space is optional unless the error
76         handling is defined to be 'strict'.
77         """
78         state = self.state
79         encoded = []
80         for c in data.upper():
81             if c in HEXDIGITS:
82                 z = HEXDIGITS.index(c)
83                 if state:
84                     encoded.append(z + (state & 0xf0))
85                     state = 0
86                 else:
87                     state = 0x100 + (z << 4)
88             elif c == ' ':      # allow spaces to separate values
89                 if state and self.errors == 'strict':
90                     raise UnicodeError('odd number of hex digits')
91                 state = 0
92             else:
93                 if self.errors == 'strict':
94                     raise UnicodeError('non-hex digit found: {!r}'.format(c))
95         self.state = state
96         return serial.to_bytes(encoded)
99 class IncrementalDecoder(codecs.IncrementalDecoder):
100     """Incremental decoder"""
101     def decode(self, data, final=False):
102         return unicode(''.join('{:02X} '.format(ord(b)) for b in serial.iterbytes(data)))
105 class StreamWriter(Codec, codecs.StreamWriter):
106     """Combination of hexlify codec and StreamWriter"""
109 class StreamReader(Codec, codecs.StreamReader):
110     """Combination of hexlify codec and StreamReader"""
113 def getregentry():
114     """encodings module API"""
115     return codecs.CodecInfo(
116         name='hexlify',
117         encode=hex_encode,
118         decode=hex_decode,
119         incrementalencoder=IncrementalEncoder,
120         incrementaldecoder=IncrementalDecoder,
121         streamwriter=StreamWriter,
122         streamreader=StreamReader,
123         #~ _is_text_encoding=True,
124     )