2 # Copyright 2020 The Pigweed Authors
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 # use this file except in compliance with the License. You may obtain a copy of
8 # https://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations under
15 """Decodes and detokenizes Base64-encoded strings in serial output.
17 The output is printed or saved to a file. Input is not supported.
22 from typing import BinaryIO, Iterable
24 import serial # type: ignore
25 from pw_tokenizer import database, detokenize, tokens
29 """Parses and return command line arguments."""
31 parser = argparse.ArgumentParser(
33 formatter_class=argparse.RawDescriptionHelpFormatter,
34 parents=[database.token_databases_parser()])
35 parser.add_argument('-d',
38 help='The serial device from which to read')
39 parser.add_argument('-b',
43 help='The baud rate for the serial device')
44 parser.add_argument('-o',
46 type=argparse.FileType('wb'),
47 default=sys.stdout.buffer,
48 help=('The file to which to write the output; '
49 'provide - or omit for stdout.'))
53 default=detokenize.BASE64_PREFIX,
54 help=('The one-character prefix that signals the start of a '
55 'Base64-encoded message. (default: $)'))
60 help=('Show error messages instead of conversion specifiers when '
61 'arguments cannot be decoded.'))
63 return parser.parse_args()
66 def _detokenize_serial(databases: Iterable, device: serial.Serial,
67 baudrate: int, show_errors: bool, output: BinaryIO,
69 if output is sys.stdout:
70 output = sys.stdout.buffer
72 detokenizer = detokenize.Detokenizer(tokens.Database.merged(*databases),
73 show_errors=show_errors)
74 serial_device = serial.Serial(port=device, baudrate=baudrate)
77 detokenize.detokenize_base64_live(detokenizer, serial_device, output,
79 except KeyboardInterrupt:
84 _detokenize_serial(**vars(_parse_args()))
88 if __name__ == '__main__':