blob: bd8f6b0df927db7c3bb8db84a9440a3a8227c7c5 [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
Kurt McKee057387c2018-02-07 22:10:38 -060021from __future__ import absolute_import
22
Chris Liechtic0c660a2015-08-25 00:55:51 +020023import codecs
24import serial
25
Chris Liechti7bb26e42016-03-08 22:59:48 +010026
27try:
28 unicode
29except (NameError, AttributeError):
30 unicode = str # for Python 3, pylint: disable=redefined-builtin,invalid-name
31
32
Chris Liechtic0c660a2015-08-25 00:55:51 +020033HEXDIGITS = '0123456789ABCDEF'
34
Chris Liechtic0c660a2015-08-25 00:55:51 +020035
Chris Liechti92df95a2016-02-09 23:30:37 +010036# Codec APIs
Chris Liechti033f17c2015-08-30 21:28:04 +020037
Chris Liechti4e34c4c2016-02-19 23:54:14 +010038def hex_encode(data, errors='strict'):
Chris Liechti7bb26e42016-03-08 22:59:48 +010039 """'40 41 42' -> b'@ab'"""
Chris Liechti4e34c4c2016-02-19 23:54:14 +010040 return (serial.to_bytes([int(h, 16) for h in data.split()]), len(data))
Chris Liechtic0c660a2015-08-25 00:55:51 +020041
Chris Liechti033f17c2015-08-30 21:28:04 +020042
Chris Liechti4e34c4c2016-02-19 23:54:14 +010043def hex_decode(data, errors='strict'):
Chris Liechti7bb26e42016-03-08 22:59:48 +010044 """b'@ab' -> '40 41 42'"""
45 return (unicode(''.join('{:02X} '.format(ord(b)) for b in serial.iterbytes(data))), len(data))
Chris Liechtic0c660a2015-08-25 00:55:51 +020046
Chris Liechti033f17c2015-08-30 21:28:04 +020047
Chris Liechtic0c660a2015-08-25 00:55:51 +020048class Codec(codecs.Codec):
Chris Liechti4e34c4c2016-02-19 23:54:14 +010049 def encode(self, data, errors='strict'):
Chris Liechti7bb26e42016-03-08 22:59:48 +010050 """'40 41 42' -> b'@ab'"""
Chris Liechti4e34c4c2016-02-19 23:54:14 +010051 return serial.to_bytes([int(h, 16) for h in data.split()])
Chris Liechti033f17c2015-08-30 21:28:04 +020052
Chris Liechti4e34c4c2016-02-19 23:54:14 +010053 def decode(self, data, errors='strict'):
Chris Liechti7bb26e42016-03-08 22:59:48 +010054 """b'@ab' -> '40 41 42'"""
55 return unicode(''.join('{:02X} '.format(ord(b)) for b in serial.iterbytes(data)))
Chris Liechtic0c660a2015-08-25 00:55:51 +020056
Chris Liechti033f17c2015-08-30 21:28:04 +020057
Chris Liechtic0c660a2015-08-25 00:55:51 +020058class IncrementalEncoder(codecs.IncrementalEncoder):
Chris Liechti4e34c4c2016-02-19 23:54:14 +010059 """Incremental hex encoder"""
Chris Liechtic0c660a2015-08-25 00:55:51 +020060
61 def __init__(self, errors='strict'):
62 self.errors = errors
63 self.state = 0
64
65 def reset(self):
66 self.state = 0
67
68 def getstate(self):
69 return self.state
70
71 def setstate(self, state):
72 self.state = state
73
Chris Liechti4e34c4c2016-02-19 23:54:14 +010074 def encode(self, data, final=False):
75 """\
76 Incremental encode, keep track of digits and emit a byte when a pair
77 of hex digits is found. The space is optional unless the error
78 handling is defined to be 'strict'.
79 """
Chris Liechtic0c660a2015-08-25 00:55:51 +020080 state = self.state
81 encoded = []
Chris Liechti4e34c4c2016-02-19 23:54:14 +010082 for c in data.upper():
Chris Liechtic0c660a2015-08-25 00:55:51 +020083 if c in HEXDIGITS:
84 z = HEXDIGITS.index(c)
85 if state:
86 encoded.append(z + (state & 0xf0))
87 state = 0
88 else:
89 state = 0x100 + (z << 4)
90 elif c == ' ': # allow spaces to separate values
91 if state and self.errors == 'strict':
92 raise UnicodeError('odd number of hex digits')
93 state = 0
94 else:
95 if self.errors == 'strict':
Chris Liechtic8f3f822016-06-08 03:35:28 +020096 raise UnicodeError('non-hex digit found: {!r}'.format(c))
Chris Liechtic0c660a2015-08-25 00:55:51 +020097 self.state = state
98 return serial.to_bytes(encoded)
99
Chris Liechti033f17c2015-08-30 21:28:04 +0200100
Chris Liechtic0c660a2015-08-25 00:55:51 +0200101class IncrementalDecoder(codecs.IncrementalDecoder):
Chris Liechti4e34c4c2016-02-19 23:54:14 +0100102 """Incremental decoder"""
103 def decode(self, data, final=False):
Chris Liechti7bb26e42016-03-08 22:59:48 +0100104 return unicode(''.join('{:02X} '.format(ord(b)) for b in serial.iterbytes(data)))
Chris Liechtic0c660a2015-08-25 00:55:51 +0200105
Chris Liechti033f17c2015-08-30 21:28:04 +0200106
Chris Liechtic0c660a2015-08-25 00:55:51 +0200107class StreamWriter(Codec, codecs.StreamWriter):
Chris Liechti4e34c4c2016-02-19 23:54:14 +0100108 """Combination of hexlify codec and StreamWriter"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200109
Chris Liechti033f17c2015-08-30 21:28:04 +0200110
Chris Liechtic0c660a2015-08-25 00:55:51 +0200111class StreamReader(Codec, codecs.StreamReader):
Chris Liechti4e34c4c2016-02-19 23:54:14 +0100112 """Combination of hexlify codec and StreamReader"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200113
Chris Liechtic0c660a2015-08-25 00:55:51 +0200114
Chris Liechtic0c660a2015-08-25 00:55:51 +0200115def getregentry():
Chris Liechti4e34c4c2016-02-19 23:54:14 +0100116 """encodings module API"""
Chris Liechtic0c660a2015-08-25 00:55:51 +0200117 return codecs.CodecInfo(
118 name='hexlify',
119 encode=hex_encode,
120 decode=hex_decode,
121 incrementalencoder=IncrementalEncoder,
122 incrementaldecoder=IncrementalDecoder,
123 streamwriter=StreamWriter,
124 streamreader=StreamReader,
Chris Liechti7bb26e42016-03-08 22:59:48 +0100125 #~ _is_text_encoding=True,
Chris Liechtic0c660a2015-08-25 00:55:51 +0200126 )