1 # Copyright 2020 The Pigweed Authors
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 # use this file except in compliance with the License. You may obtain a copy of
7 # https://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations under
14 """Console for interacting with pw_rpc over HDLC.
16 To start the console, provide a serial port as the --device argument and paths
17 or globs for .proto files that define the RPC services to support:
19 python -m pw_hdlc_lite.rpc_console --device /dev/ttyUSB0 sample.proto
21 This starts an IPython console for communicating with the connected device. A
22 few variables are predefined in the interactive console. These include:
24 rpcs - used to invoke RPCs
25 device - the serial device used for communication
26 client - the pw_rpc.Client
28 An example echo RPC command:
30 rpcs.pw.rpc.EchoService.Echo(msg="hello!")
36 from pathlib import Path
38 from typing import Collection, Iterable, Iterator, BinaryIO
43 from pw_hdlc_lite.rpc import HdlcRpcClient
45 _LOG = logging.getLogger(__name__)
49 """Parses and returns the command line arguments."""
50 parser = argparse.ArgumentParser(description=__doc__)
51 parser.add_argument('-d',
54 help='the serial port to use')
55 parser.add_argument('-b',
59 help='the baud rate to use')
63 type=argparse.FileType('wb'),
64 default=sys.stdout.buffer,
65 help=('The file to which to write device output (HDLC channel 1); '
66 'provide - or omit for stdout.'))
67 parser.add_argument('proto_globs',
69 help='glob pattern for .proto files')
70 return parser.parse_args()
73 def _expand_globs(globs: Iterable[str]) -> Iterator[Path]:
75 for file in glob.glob(pattern, recursive=True):
79 def _start_ipython_terminal(client: HdlcRpcClient) -> None:
80 """Starts an interactive IPython terminal with preset variables."""
81 local_variables = dict(
83 channel_client=client.client.channel(1),
84 rpcs=client.client.channel(1).rpcs,
87 print(__doc__) # Print the banner
88 IPython.terminal.embed.InteractiveShellEmbed().mainloop(
89 local_ns=local_variables, module=argparse.Namespace())
92 def console(device: str, baudrate: int, proto_globs: Collection[str],
93 output: BinaryIO) -> int:
94 """Starts an interactive RPC console for HDLC."""
95 # argparse.FileType doesn't correctly handle '-' for binary files.
96 if output is sys.stdout:
97 output = sys.stdout.buffer
100 proto_globs = ['**/*.proto']
102 protos = list(_expand_globs(proto_globs))
105 _LOG.critical('No .proto files were found with %s',
106 ', '.join(proto_globs))
107 _LOG.critical('At least one .proto file is required')
110 _LOG.debug('Found %d .proto files found with %s', len(protos),
111 ', '.join(proto_globs))
113 _start_ipython_terminal(
114 HdlcRpcClient(serial.Serial(device, baudrate), protos, output))
119 return console(**vars(_parse_args()))
122 if __name__ == '__main__':